How do I loop trough variables
Show older comments
How do I loop throug variables like this?
a=1;
b=2;
c=3;
for Q=[a b c]
Y=Q
end
The result i would like is:
y = 1
y = 2
y = 3
5 Comments
Guillaume
on 6 Mar 2020
"The result i would like is: [...]"
Which is what your code does. So what is your question?
"The result i would like is..."
And that is exactly what you will get using your own code:
>> a=1;
>> b=2;
>> c=3;
>> for Q=[a b c]
y=Q
end
y = 1
y = 2
y = 3
If your own code gives you exactly the result that you expect, where is the problem?
René Moerman
on 6 Mar 2020
Are the variables actually tables which would show in the variable browser as a 9x14 table, or cell arrays which would show in the variable browser as 9x14 cell?
Also, what do you want to do with your loop?
René Moerman
on 6 Mar 2020
Answers (1)
"Why is that?"
Your confusion stems from several things.
- [] square brackets are a concatenation operator, not a "list" operator (which MATLAB does not have). So you took three 9x14 cell arrays and concatenated them horizontally to get one 9x42 cell array (not a "list" of separate arrays as you seemed to be expecting). If you want to store several arrays in a container, then use a cell array.
- Without realizing it, you are looping over the columns of that 9x42 cell array. The for documentation explains that if the values to be iterated over are a non-vector array, then for will iterate over its columns. I have never seen anyone rely on this "feature".
I would avoid your approach of iterating over data or over arrays: it is much more robust to iterate over indices:
C = {arr1,arr2,arr3}; % cell array
for k = 1:numel(C)
Y = C{k};
... do whatever with Y
end
2 Comments
Guillaume
on 6 Mar 2020
"I have never seen anyone rely on this "feature"."
I use it sometimes, but it is indeed very rare that you just want to iterate over columns without knowing their indices.
Guillaume
on 6 Mar 2020
"would avoid your approach of iterating over data or over arrays"
Totally agree.
Even better would be to avoid creating these numbered arrays in the first place. There should only be one variable to start with, either a cell array or in this case since all the arrays are the same size, a 3D matrix.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!