Name a few variables from a vector

조회 수: 4 (최근 30일)
Sam Sun
Sam Sun 2019년 11월 13일
답변: Steven Lord 2019년 11월 13일
If I need to get some variables values from a vector in Matlab, I could do, for instance,
x = A(1); y = A(2); z = A(3);
or I think I remember I could do something like
[x, y, z] = A;
However Matlab is not recognizing this format. what was the correct syntax? Thanks!!

답변 (1개)

Steven Lord
Steven Lord 2019년 11월 13일
There is a function named deal that looks like it does something like what you're asking, but that assigns each of its inputs to one of the outputs in turn. When you call a function you can specify multiple outputs, but what you described (to "unpack" a vector or matrix into individual variables) won't work.
Consider two simple examples. What should the size of each of the outputs be in this first case and why did you choose those particular sizes?
v1 = 1:4;
[x1, y1, z1] = v1;
size(x1) % ?
size(y1) % ?
size(z1) % ?
How about for this example?
v2 = 1:2;
[x2, y2, z2] = v2;
size(x2) % ?
size(y2) % ?
size(z2) % ?
If you need to give a name to a small and fixed number of elements of a larger vector, I'd do so explicitly. For example, if you have a vector y with two elements and you're going to reference each one repeatedly, naming y1 = y(1) and y2 = y(2) to save one character each time (or to make the code look more like an equation for which it's the implementation) may be appropriate. If you're trying to create the equivalent of a large number of variables like x1, x2, x3, ... x500 (for example) that's strongly discouraged.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by