필터 지우기
필터 지우기

Protect the size of a preallocated matrix

조회 수: 2 (최근 30일)
Martijn Kortenhoeven
Martijn Kortenhoeven 2020년 2월 22일
댓글: Martijn Kortenhoeven 2020년 2월 22일
I am trying to protect the preallocated size of a matrix, to avoid making mistakes, and getting/giving an error when the matrix size changes, without having to check the size everytime I do an iteration. Consider the following code.
>> A = zeros(2,2);
>> A(1,3) = 5
A =
0 0 5
0 0 0
I am aware I can check the size of the matrix everytime I change it. I am wondering however, whether Matlab can give me an error/warning, since you do get a warning with the following code:
A = [];
for i = 0:5
A = [A;eye(2)];
end % Warning: The variable A appears to change size at every iteration. Consider preallocating for speed.
If Matlab could give an error, I would preferably get this in the command window.

채택된 답변

Giuseppe Inghilterra
Giuseppe Inghilterra 2020년 2월 22일
Hi,
in MATLAB numeric arrays are free to change size, i.e. if you add an element outside intial defined dimension, then array will be extended and no warning/error is shown.
You can define a user defined class (with a object oriented programming approach) in order to fix dimension of your numeric arrays. Otherwise you should check frequently size of your array and show a custom message on command window (by usind disp function) if size changes along code (but it is not a real solution).

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by