Note: This is not about preallocating variable in a loop. This is for general case.
For instance:
a(10,10) = 10; % the rest are filled with zeros
%or
a = zeros(10,10);
a(10,10) = 10;

댓글 수: 4

There was a Question in which people did some timing. The answer is not always obvious.
The larger question at the time also asked about the timing of assigning a constant to the matrix. For example is
5*ones(10,10)
faster than
5+zeros(10, 10l
Or
repmat(5, 10, 10)
madhan ravi
madhan ravi 2019년 8월 15일
Thank you for the response sir Walter. Even a while ago , did some experiments and found out that multiplying a constant against ones() were always faster. Forgot this point , sorry :/. So with my above two approaches, is the first option a good way of coding?
madhan ravi
madhan ravi 2019년 8월 15일
Thank you sir Walter :)

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

답변 (1개)

Adam Danz
Adam Danz 2019년 8월 15일
편집: Adam Danz 2019년 8월 15일

1 개 추천

In terms of speed, the 2nd option is 3.0 times faster on average (p<0.0001, Wilcoxon Signed Rank; 1 million individually timed iterations of the following 2 options).
a = []; % to reset a upon each loop
a(10,10) = 10;
% versus
a = []; % to reset a upon each loop
a = zeros(10,10);
a(10,10) = 10;
Declaring 'a' as zeros and then filling in the index (10,10) could also avoid other errors that option 1 may impose if 'a' is already a variable or function that exists.
Lastly, I think the 2nd option is more readable. Upon first glace of the first option, I'm wondering where 'a' came from.

댓글 수: 3

madhan ravi
madhan ravi 2019년 8월 15일
Thanks Adam for the answer. I knew the differences in speed. I mean't to ask whether if the first option also considered as a good way to code.
Rik
Rik 2019년 8월 15일
There is nothing inherently wrong with the first option, but because it can cause confusion, you should add a comment there. It is also important to make sure that a doesn't exist before this executes.
madhan ravi
madhan ravi 2019년 8월 15일
Thanks Rik.

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

카테고리

도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2019년 8월 15일

댓글:

2019년 8월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by