Name a few variables from a vector
4 次查看(过去 30 天)
显示 更早的评论
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!!
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!