assigning multiple outputs from a vector

If I have a vector of a known length, let's say X = [ 1 2 3 4 ], is there an easy way to assign the elements of the vector to different variables? For example, I know I can do:
a = X(1); b = X(2); c = X(3); d = X(4);
Is there a function that will allow me to do something like [a b c d] = X? (I know this doesn't work, its just an example of what I am trying to do).

 채택된 답변

Matt J
Matt J 2014년 3월 11일

1 개 추천

Xcell=num2cell(X);
[a,b,c,d]=deal(Xcell{:});

댓글 수: 3

Victor
Victor 2014년 3월 11일
Thanks for the quick response. Is there a way to do Xcell{:} without having to declare Xcell? something similar to num2cell(X){:}? I'd like to have this in one line if possible.
Matt J
Matt J 2014년 3월 11일
편집: Matt J 2014년 3월 11일
No, there is no way.
But you can use the function below to encapsulate everything into one function call [a,b,c,d]=vout(X)
function varargout=vout(C)
%
%Takes the elements of a cell or numeric array and assigns them to separate varargout
%
% [argout1,argout2,...]=vout(X)
%
if isnumeric(C), C=num2cell(C); end
C=C(:).';
Victor
Victor 2014년 3월 12일
Thanks, Matt. That worked great.

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

추가 답변 (0개)

카테고리

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

질문:

2014년 3월 11일

댓글:

2014년 3월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by