Need syntax help for creating loop that is dependent on array size

I'm looking to create a loop that runs some calculations for any 2x2 array that is input and generates a warning for any other sized array that is input. If a 3x3 input is entered, i'll need a different warning than if any random size is entered. I'm thinking something like below, but am struggling with the syntax. Thanks in advance
if size(A) = (2 2)
calculations
elseif size(A) = (3 3)
disp('System not designed to evaluate 3x3 matrices')
elseif size(A) ~= (2 2,3 3)
disp('An invalid array has been entered')

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 26일
편집: Azzi Abdelmalek 2012년 11월 26일
s=size(A);
if all(s==[2 2])
%do
elseif all(s==[3 3])
disp('System not designed to evaluate 3x3 matrices')
else
disp('An invalid array has been entered')
end

댓글 수: 5

Thank you very much!
This will error if A is like:
A = ones(2,2,3);
Better to do:
[M,N,K]= size(A);
Now pass this result to the conditional. Perhaps a call to NDIMS, depending on the exact situation.
It depends on what he's doing. If it's a problem we can add to the condition & numel(s)==2 or ndims(a)==2
s=size(A);
if all(s==[2 2])& numel(s)==2
%do
elseif all(s==[3 3])& numel(s)==2
disp('System not designed to evaluate 3x3 matrices')
else
disp('An invalid array has been entered')
end
You will need to add the call to NDIMS or NUMEL first, or there will still be an error. (Use && instead of &)
A = ones(2,2,3);
S = size(A);
if all(S==[2,2] && ndims(A)==2)
disp('here') % Errors!
end
if all(ndims(A)==2 && S==[2,2])
disp('here') % No error. (call to ALL not necessary)
end
Or, simplified:
A = ones(2,2,3);
[M,N,K]= size(A);
if K==1 && [M,N]==[2,2]
disp('here') % No error
end
You are right Matt, to avoid problems I will use (maybe A=rand(4,2,1,3))
s=size(A)
n=size(A,1);
m=size(A,2)
if n==2 & m==2 & numel(s)==2
%do
elseif n==3 & m==3 & numel(s)==2
disp('System not designed to evaluate 3x3 matrices')
else
disp('An invalid array has been entered')
end

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

추가 답변 (1개)

카테고리

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

태그

질문:

2012년 11월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by