Cannot perform null assignment from variable

The following code "works" (deletes the 3rd element of A, or the third page, if the first two dimensions are not 1 & 1):
A = nan(1,1,3);
A(3) = [];
This modification breaks the functionality and throws an error: "Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 0-by-0."
A = nan(1,1,3);
empty_scalar = [];
A(3) = empty_scalar;
I don't understand what's going on here -- why can't I do the same null assignment from a variable? Is "= []" special syntax?
I'd like to be able to automate the process of either assigning or deleting elements/columns/pages of some arbitrarily-sized array. How can I do this, given the above behavior?
Thanks.

댓글 수: 1

The first one is deletion.
The second one is assignment (as the error states as well).

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

 채택된 답변

Matt J
Matt J 2023년 11월 13일
편집: Matt J 2023년 11월 13일
Yes, it is special syntax. I agree it is strange behavior, but one workaround is,
A = nan(1,1,3);
empty_scalar = [];
if isempty(empty_scalar)
A(3) = [];
else
A(3)=empty_scalar;
end
A
A =
A(:,:,1) = NaN A(:,:,2) = NaN

댓글 수: 1

Aaron
Aaron 2023년 11월 13일
It's interesting to me that '= []' is special behavior (for subscripted assignment only?); until today I always assumed it was somehow assigning a 0-by-0 array to all entries in the given slices.
I'm not sure the subsasgn workaround will be any prettier than what I ended up with, which was just some nested if's with different versions of the assignment statement (which had to assign multiple outputs to slices of different arrays).
Thanks for your help.

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

추가 답변 (1개)

Matt J
Matt J 2023년 11월 13일
Another workaround is to call subsasgn direclty,
A = nan(1,3);
empty_scalar = 4;
A=subsasgn(A, struct('type','()','subs',{{3}}) , empty_scalar)
A = 1×3
NaN NaN 4
empty_scalar = [];
A=subsasgn(A, struct('type','()','subs',{{3}}) , empty_scalar)
A = 1×2
NaN NaN

카테고리

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

제품

릴리스

R2023a

태그

질문:

2023년 11월 13일

댓글:

2023년 11월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by