Define an input that is ONLY a 3-by-4 matrix

3 次查看(过去 30 天)
Hi.
I have a function called modify that I want to perform a series of tasks. How do I specifiy my input so that only a 3-by-4 matrix can be entered as input matrix A?
The following is my code:
function [ output,A1,A2,A3,A4,A5,A6 ] = modify( A )
%modify a given 3-by-4 matrix A
% output: a one-dimensional array consisting of y1,y2,y3,and y4
y1=A(end);
y2=A(2,3);
A1=A(2:3,2:3);
A2=A(5:7);
A3=A;
A3(3,2)=6;
A3=[A3 zeros(3,1)];
A4=2*A;
A5=A';
A6=[4 0 3];
X=[3 3 3; 1 0 0; 2 5 1];
A6=[A6; X];
A6=A5.*A6;
A6=A6([2:end],:);
y3=size(A6,1);
y4=sum(A6>10);
output=[y1 y2 y3 y4];
end

回答(1 个)

Cedric
Cedric 2017-9-26
编辑:Cedric 2017-9-26
You can use specialized functions described here:
but for something as small as that, I would just go for:
assert( isequal(size(A), [3, 4]), 'Error message here..' ) ;
at the top of the function. This is equivalent to the following conditional statement:
if ~isequal( size(A), [3, 4] )
error( 'Error message here ..' ) ;
end
but more concise/compact.
  1 个评论
Jan
Jan 2017-9-27
+1: Both methods are nice and efficient. Another method:
validateattributes(A, {'numeric'}, {'size',[4,6,2]})
This is very powerful and useful. But in consequence it has a certain overhead.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by