Output to an array or matrix
조회 수: 6 (최근 30일)
이전 댓글 표시
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
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!