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

조회 수: 3 (최근 30일)
amateurintraining
amateurintraining 2017년 9월 26일
댓글: Jan 2017년 9월 27일
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