Info
此问题已关闭。 请重新打开它进行编辑或回答。
How to get the relsults in different matrix after for loop
1 次查看(过去 30 天)
显示 更早的评论
Hello all,
I am working on a engine in which i want a result at different rpm... let i be the different rpm and A be the fuel consumption
B and C as the factor for calculating them.
At the end i want to have 3 matrices
A1 when i = 1
A2 when i = 2
A3 when i = 3
B=[1 1; 1 1]
C=[2 2;2 2]
for i=1:3
A= B*i+C*i
end
What should i add up in this program to get the desired result
1 个评论
Stephen23
2019-1-22
编辑:Stephen23
2019-1-22
Using numbered variables is a sign that you are doing something wrong.
Putting numbers into variable names like that treats those numbers as pseudo-indices, which are slow, complex, and buggy to work with. It is much simpler to use real indices, which are neat, efficient, and very easy to debug. Unlike what you are trying to do.
Read this to know more:
For example, you could easily use a cell array:
A = cell(1,3);
for k = 1:3
A{k} = B*k + C*k;
end
but probably the best solution would be to learn how to use arrays and write vectorized code. Then you can trivially avoid the loop entirely and write simpler, more efficient code:
V = reshape(1:3,1,1,[]);
A = B.*V + C.*V
回答(2 个)
Walter Roberson
2019-1-22
1 个评论
Stephen23
2019-1-22
编辑:Stephen23
2019-1-22
"why is it not recommended... can u please explain"
Did you try reading the link that Walter Roberson gave you?
" right now i am new to matlab n wanna learn "
Is that why you accepted an answer which shows you how to write slow, complex, inefficient, obfuscated, hard-to-debug MATLAB code? If you want to learn, try reading the link that Walter Roberson gave you.
StefBu
2019-1-22
编辑:StefBu
2019-1-22
Hi if you really want to use eval,try this code:
for i=1:3
tempName = ['A', num2str(i)];
eval([tempName '= B*i +C*i;']);
end
Greetings
Stefan
1 个评论
Stephen23
2019-1-22
编辑:Stephen23
2019-1-22
Or you could use this opportunity to learn why this is a really slow, complex, inefficient, buggy way to write code. For example, by reading the MATLAB documenation, which clearly 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."
Beginners would improve their MATLAB code quite a lot by following the advice in the MATLAB documentation. Read more here:
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!