Feeding strings into function xcov without quotation marks

1 view (last 30 days)
Dear all,
I'm trying to compare various signals (vectors) using the function xcov. The names of these vectors all have the form "condition_meanrate", with the prefix "condition" being variable (so e.g. I have a files called 'cedo_meanrate', sodo_meanrate', 'sosp_meanrate' etc. The variable prefixes are stored in a separate vector). I created for-loops and am using
arg_1=sprintf('%s',x,'_meanrate')
arg_2=sprintf('%s',x,'_meanrate')
(with x being a char array containing the respective prefix) to feed the respective signal-vector into the xcov function:
[xcov_vec,lags]=xcov(arg_1,arg_2,'coeff').
Now the problem is that the names are fed in the way as if I'd type them using quotation marks, so like xcov('cedo_meanrate','sosp_meanrate','coeff'). Then xcov seems to compare the actual strings instead of the signal values. If I manually type xcov(cedo_meanrate,sosp_meanrate,'coeff') it works. I found a similar problem here: https://answers.yahoo.com/question/index?qid=20120416085207AAsXhqN But looking into the xcov script it says:
function [xycov,lags] = xcov(x,y,option1,option2)
I don't really know what to do now. Is there a way to feed the names into the function so that they appear as if the didn't had quotation marks?
Thanks very much! Best, Felix

Accepted Answer

dpb
dpb on 1 Apr 2015
The respondents to the question at the link answered a different question than that posed -- or, more correctly, they read the question asked literally rather than inferring the underlying problem that the user has like yours of trying to use character variables as variable names. The answer to the question is "Don't do that!"; it leads to nothing but grief. Instead use named structure fields or ordinary arrays instead and write your functions/scripts so they're not dependent upon 'poofing' variables into the workspace. See the FAQ on why not and alternatives...

More Answers (1)

Stephen23
Stephen23 on 1 Apr 2015
"Is there a way to feed the names into the function so that they appear as if the didn't had quotation marks?"
Probably
Is it a good idea?
No
Creating variables like this is poor programming style, and will only make your own life difficult. Just like many things in life, just because you can do something is not synonymous with it being a good idea to do it. This is poor practice as has been explained many times on this forum, and is not recommended by MATLAB themselves:
In case you are interested, here are some pages explaining why dynamically assigning variable names is a really bad idea in MATLAB:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!