When assignment is allowed?

8 ビュー (過去 30 日間)
Bruno Luong
Bruno Luong 2023 年 8 月 6 日
編集済み: Bruno Luong 2023 年 8 月 7 日
The question concerns the requirement of the sizes of the assignment between two arrays.
To my great surprise this is allowed
lhs = zeros(3,4,5);
rhs = ones(4,5);
lhs(1,:,:) = rhs;
I would thought the last statement would throw an error
"Unable to perform assignment because the size of the left side is 1-by-4-by-5 and the size of the right side is 4-by-5."
but obviously it's not.
Can someone points me to the official document that explains such assigment is allowed and how?
  2 件のコメント
Paul
Paul 2023 年 8 月 6 日
The documentation on how assignment works is nonexistent as far as I can tell.
Will be interested to see if there is a doc-based answer, or if this is a case of "Matlab knows what you want"
Also works for other dimensions, so the leading unity dimension is not some sort of special case
lhs = zeros(3,4,5);
rhs = ones(3,5);
try
lhs(:,2,:) = rhs;
disp('success');
catch
disp('error');
end
success
the cyclist
the cyclist 2023 年 8 月 6 日
This would have taken me by surprise as well. I did not find this behavior in the documentation, but I did find it in this blog post from @Loren Shure. It is in the section "Retaining Array Shape During Assignment".

サインインしてコメントする。

採用された回答

Matt J
Matt J 2023 年 8 月 6 日
編集済み: Matt J 2023 年 8 月 6 日
The relevant documentation is at,
Singleton dimensions are ignored when determining if the right and left hand sides have matching dimensions.
x=1:8
x = 1×8
1 2 3 4 5 6 7 8
x(1:3)=[10;20;30] %assign 3x1 into a 1x3 data region
x = 1×8
10 20 30 4 5 6 7 8
  8 件のコメント
Rik
Rik 2023 年 8 月 7 日
It really does help for 3D images. The mri.mat example dataset is [row,col,color,page] (even though it is grayscale), but most other places will use [row,col,page,color]. This sytax allow subindexing and swapping conventions with relative easy, without having to use permute or squeeze every second line
Bruno Luong
Bruno Luong 2023 年 8 月 7 日
編集済み: Bruno Luong 2023 年 8 月 7 日
@Rik understood why you have 2 different orders of dimensions. In one case you want to process by color, in other you want to process by chromatic images.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by