Info

# How to get the relsults in different matrix after for loop

1 view (last 30 days)
Shubham Mohan Tatpalliwar on 22 Jan 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
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
Stephen23 on 22 Jan 2019
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.
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

Walter Roberson on 22 Jan 2019
We recommend against that firmly.
Stephen23 on 22 Jan 2019
"why is it not recommended... can u please explain"
" 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 on 22 Jan 2019
Edited: StefBu on 22 Jan 2019
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