Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to get the relsults in different matrix after for loop

조회 수: 1 (최근 30일)
Shubham Mohan Tatpalliwar
Shubham Mohan Tatpalliwar 2019년 1월 22일
마감: MATLAB Answer Bot 2021년 8월 20일
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
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
Walter Roberson 2019년 1월 22일
We recommend against that firmly.
  댓글 수: 1
Stephen23
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
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
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!

Translated by