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 日

0 投票

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 件のコメント

Flip
Flip 2012 年 11 月 26 日
Thank you very much!
Matt Fig
Matt Fig 2012 年 11 月 26 日
編集済み: Matt Fig 2012 年 11 月 26 日
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.
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 11 月 26 日
編集済み: Azzi Abdelmalek 2012 年 11 月 26 日
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
Matt Fig
Matt Fig 2012 年 11 月 26 日
編集済み: Matt Fig 2012 年 11 月 26 日
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
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 11 月 26 日
編集済み: Azzi Abdelmalek 2012 年 11 月 26 日
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 についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by