Matrix call inside a for loop
显示 更早的评论
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 个评论
José-Luis
2017-8-16
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
2017-8-28
采纳的回答
更多回答(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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!