Output to an array or matrix

조회 수: 6 (최근 30일)
Daniel Lee
Daniel Lee 2020년 11월 2일
댓글: Stephen23 2020년 11월 2일
Using For and If loop, I got 5 separate outputs, ans = 1, 2, 3, 4, 5
Is there a way to automatically create an array with above output?
End result should be 1x5 matrix like A= [1 2 3 4 5]
Thank you
  댓글 수: 3
Daniel Lee
Daniel Lee 2020년 11월 2일
not sure why you put a link for preallocation. isnt that for optimization?
Stephen23
Stephen23 2020년 11월 2일
"not sure why you put a link for preallocation. isnt that for optimization?"
Not just for optimization. I linked to that page for several reasons:
1- primarily because it answers your question. You asked "Is there a way to automatically create an array with above output?", and the page I linked to
shows complete working examples of how to store data in a loop (using indexing).
2- it also gives you bonus information that explains why preallocation is useful for efficiency reasons.
3- another important reason for preallocation: it avoids errors that result from already having an existing variable of the same name in the workspace (errors caused by incompatible or unexpected types or array sizes. MATLAB is weakly-typed, which is both a blessing and a curse...).
4- optimization is easiest when you learn how to follow good code practices right from the start. Following good practices actually makes your life easier because you will spend less of your time debugging code, or rewriting code once you realize how slow it is, or figuring out how to access data. This benefits you.
5- The link you gave here does not use preallocation, which is not good practice (see the above points). Sadly, this is how bad coding practices propagate. In order to help any future reader who might be interested in writing efficient, robust code I post links to the MATLAB documentation and reputable explanations.
6- because I believe that all users have the right to good information (and also to know where to find it).
So my answer to your comment is "because it answers your original question and gives you extra advice that you will find useful if you want to learn how to write efficient, robust MATLAB code".

댓글을 달려면 로그인하십시오.

답변 (1개)

James Tursa
James Tursa 2020년 11월 2일
Colon operator.
A = 1:5;
  댓글 수: 3
Daniel Lee
Daniel Lee 2020년 11월 2일
Let me give you an example. If you run below command, you'll get 5 different outputs. Is there a way to automatically generate a matrix with those outputs?
>> a=1:5;
>> sum_a=0
>> for i=1:length(a)
sum_a = sum_a + a(i)
end
Daniel Lee
Daniel Lee 2020년 11월 2일

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by