Loop through list of variable in workspace to get and store in matrix
Mostra commenti meno recenti
How can i loop through list of variable 'selected' in workspace to get and store in one matrix (h).
it only stores the last matrix using my code. please help
clear
A=[1, 2, 3]'
B=[3,4,5]'
C=[3,7,9]'
x=who
selected={'A', 'B' 'C'};
m=length(selected)
h=zeros(3,m)
for cv = x
y= eval(sprintf('%1$s', cv{m}))
h(:,cv) = y
end
%%Result
A=[1 3 3;2 4 7; 3 5 9]
4 Commenti
dpb
il 23 Gen 2021
Man there's been a run on poofing variables into workspace recently... :(
In short, this is highly discouraged coding, as you've already discovered it is very difficult to get right and even more difficult to debug.
If it is intended to need to do something like this, create the data initially either as a cell array or perhaps a named struct so can programmatically do things with it outside of being forced to use eval
Stephen23
il 23 Gen 2021
"Loop through list of variable in workspace..."
... usually indicates a major flaw in data design or code design.
The MATLAB documentation states "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Rather than telling us about your slow, complex, inefficient, buggy approach, you should tell us what you are trying to achieve.
joms
il 24 Gen 2021
"Do you have more efficient method of extracting specifice struct data from workspace? thank you."
NO, there is no efficient way to do this: once the data is in the workspace as lots of separate variables, you have forced yourself into writing slow, complex, inefficient, obfuscated code to try and access it. The best approach is to avoid needing to do this, which is easy to do.
"the data is from a matfile with saved signal, each has 1xn matrix."
Then you can easily write neat, simple, efficient code by loading into one variable when you load the data into the workspace, exactly as the MATLAB documentation shows:
It is much better to avoid the bad situation that you are getting yourself into, by simply writing simple robust code, e.g. by loading into an output variable:
S = load(..)
And storing that data in one variable, exactly as the documentation shows.
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!