Output to an array or matrix

3 views (last 30 days)
Daniel Lee
Daniel Lee on 2 Nov 2020
Commented: Stephen23 on 2 Nov 2020
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 Comments
Daniel Lee
Daniel Lee on 2 Nov 2020
not sure why you put a link for preallocation. isnt that for optimization?
Stephen23
Stephen23 on 2 Nov 2020
"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".

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 2 Nov 2020
Colon operator.
A = 1:5;
  3 Comments
Daniel Lee
Daniel Lee on 2 Nov 2020
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

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!