Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

How to get the relsults in different matrix after for loop

1 Ansicht (letzte 30 Tage)
Shubham Mohan Tatpalliwar
Shubham Mohan Tatpalliwar am 22 Jan. 2019
Geschlossen: MATLAB Answer Bot am 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
  1 Kommentar
Stephen23
Stephen23 am 22 Jan. 2019
Bearbeitet: Stephen23 am 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.
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

Antworten (2)

Walter Roberson
Walter Roberson am 22 Jan. 2019
We recommend against that firmly.
  1 Kommentar
Stephen23
Stephen23 am 22 Jan. 2019
Bearbeitet: Stephen23 am 22 Jan. 2019
"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
StefBu am 22 Jan. 2019
Bearbeitet: StefBu am 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
  1 Kommentar
Stephen23
Stephen23 am 22 Jan. 2019
Bearbeitet: Stephen23 am 22 Jan. 2019
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!

Translated by