Matrix call inside a for loop
Ältere Kommentare anzeigen
I probably have an easy equation regarding the correct vector calling inside a for-loop. I’m trying to conduct the same calculation for let’s say different 4 vectors. Therefore I would like to use a for-loop. Simplified, it should look like this:
a_1 = [1 2 3 4 5]
a_2 = [2 3 4 5 6]
a_3 = [3 3 4 5 7]
a_4 = [4 3 4 5 8]
for i=1:4
b(i)=a_(i)/60
end
4 Kommentare
José-Luis
am 16 Aug. 2017
Bad idea. Don't use dynamic variable names, it is horrible code. Use cell arrays instead.
a_1 = [1 2 3 4 5]
a_2 = [2 3 4 5 6]
a_3 = [3 3 4 5 7]
a_4 = [4 3 4 5 8]
DO NOT DO THIS. Read this to know why: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
It is much simpler to use a matrix:
a = [1 2 3 4 5; 2 3 4 5 6; 3 3 4 5 7; 4 3 4 5 8]
then your task is trivially easy:
b = a./60
Did you see what I did there? By storing the data in one array I turned your difficult-to-solve task into one trivially easy operation. Writing MATLAB code should be easy, and it is when you store your data in arrays.
"I want to invoke different matrix/arrays to use them inside subplot and for further calculations."
We already explained why this is a bad idea: it will make your code slow, buggy, and complex. It is so hard you had to ask on an internet forum for help. Why bother? If you simply stored your data in one array then you can trivially use indexing: indexing is simple, fast, neat, efficient, easy to debug.
Felix
am 28 Aug. 2017
Akzeptierte Antwort
Weitere Antworten (1)
data = {a1,a2,a4,a4}; %Better yet, use a cell array from start
result = cell(size(data));
for ii = 1:numel(data)
b(ii) = a{ii}./60;
end
You could also use cellfun() to avoid looping.
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!