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')

 Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 26 de Nov. de 2012
Editada: Azzi Abdelmalek el 26 de Nov. de 2012
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 comentarios

Thank you very much!
Matt Fig
Matt Fig el 26 de Nov. de 2012
Editada: Matt Fig el 26 de Nov. de 2012
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
Matt Fig
Matt Fig el 26 de Nov. de 2012
Editada: Matt Fig el 26 de Nov. de 2012
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

Iniciar sesión para comentar.

Categorías

Etiquetas

Preguntada:

el 26 de Nov. de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by