Plotting by string name
Mostra commenti meno recenti
Hey all, simple question (I think). I have a matrix named sxx and one named t. I wanna plot(t,sxx) but I wanna use strings, meaning I have a string filename called 'sxx' and I wanna be able to plot(t,sprintf('%s',filename)). The latter of course doesn't work, since filename is a 1x3 char array whereas sxx is a Nx1 double matrix. Thanks!
Risposte (2)
Walter Roberson
il 5 Mar 2016
data = load(filename);
plot(t, data);
If the file is a .mat file and the variable stored in it is named "sxx" then,
data = load(filename);
plot(t, data.sxx)
If the file is a .mat file and the variable stored in it is the same as the .mat file name then,
data = load(filename);
plot(t, data.(filename));
4 Commenti
Vas Nas
il 5 Mar 2016
Easy: don't store separate variables. Store one structure with fields, and access the fields using strings:
S.field1 = [...];
S.field2 = [...];
C = fieldnames(S);
for k = 1:numel(C)
S.(C{k}) % use a string to access each fields data
end
Whatever you do, do NOT try to access lots of varaible names dynamically. This is a slow and buggy way to write code, not matter how much beginners love to keep re-inventing it. Read this to know why you should not try to access your variables dynamically:
How did the variables get into your workspace?
It is easy to refer to fieldnames using strings. The example in my first comment shows this: C is a cell array of the fieldnames (i.e. strings). Read this to know more about using strings to access fieldnames:
And try it yourself:
>> S.first = 3;
>> S.test = 'cat';
>> S.another = NaN;
>> S.('test')
ans =
cat
You could load your data into a variable, or use textscan. Either of these will work in a loop: use indexing into an ND array, or a cell array, or use dynamic fieldnames of a structure. It is up to you, and what suits you best.
Image Analyst
il 5 Mar 2016
Regarding your clarification, I'll assume your strings are something you get somehow from your user, like they select a predefined name from a popup control, or they type in a name into an edit text control. So to plot the desired string variable, you can use strcmp
if strcmp(lower(theString), 'sxx')
plot(t, sxx, 'b*=', 'LineWidth', 2, 'MarkerSize', 14);
grid on;
elseif strcmp(lower(theString), 'y')
plot(t, y, 'b*=', 'LineWidth', 2, 'MarkerSize', 14);
grid on;
elseif strcmp(lower(theString), 'syy')
plot(t, syy, 'b*=', 'LineWidth', 2, 'MarkerSize', 14);
grid on;
elseif strcmp(lower(theString), 'whatever')
plot(t, whatever, 'b*=', 'LineWidth', 2, 'MarkerSize', 14);
grid on;
end
Categorie
Scopri di più su Characters and Strings in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!