array dimensions equivalence check?

조회 수: 22 (최근 30일)
Walter Roberson
Walter Roberson 2012년 1월 4일
편집: Bruno Luong 2022년 4월 23일
You would think I would know this by now, but I never had reason to program it before.
Is there a good idiom for efficiently checking that two arrays are the same size or are row and column vectors of the same length?
For example, this kind of check would be used to find out whether two arrays are assignment-compatible, or to find out if two arrays are compatible for plot() purposes.
The code I have come up with feels overly complicated:
szA = size(A);
szB = size(B);
if isequal(szA,szB) || ...
(sum(szA==1) == 1 && sum(szB==1) == 1 && ...
numel(szA)==2 && numel(szB)==2) && ...
prod(szA) == prod(szB))
Which is to say, the sizes can be identical, or they can both be 2 dimensional with exactly one of the dimensions of each being 1, and the number of elements the same between the two.
This kind of check must be programmed all over the place. Perhaps there is a utility routine that I overlooked?
  댓글 수: 2
Paulo Abelha
Paulo Abelha 2016년 9월 21일
편집: Walter Roberson 2016년 9월 21일
Hello Walter,
I have implemented a function that might help you:
Best regards,
Bruno Luong
Bruno Luong 2022년 4월 23일
편집: Bruno Luong 2022년 4월 23일
Your test return false for
A = [];
B = zeros(1,0);
however plot works just fine
plot(A,B)
or Assignment
X = rand();
X(1,[])=X([],[]) % B on lhs, A on rhs
X = 0.6365

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

채택된 답변

David Young
David Young 2012년 1월 4일
One alternative:
isequal(size(A), size(B)) || (isvector(A) && isvector(B) && numel(A) == numel(B))
  댓글 수: 3
Adam Wyatt
Adam Wyatt 2021년 11월 18일
This will return true if A is a row vector and B is a column vector (or vice versa). If you care about that:
isequal(size(A), size(B)) || ( ...
((iscolumn(A) && iscolumn(B)) || (isrow(A) && isrow(B))) ...
&& isequal(numel(A), numel(B)))
Ahmed
Ahmed 2022년 4월 23일
This seems not working for 3-D arrays or higher. Therefore, I implemented a more general function below.

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

추가 답변 (0개)

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by