I have a function "f" that returns a 1x2 vector, and I need to make a 3x2 matrix M by stacking the outputs f(x1), f(x2), f(x3) on top of each other, but Matlab won't parse it.

7 次查看(过去 30 天)
First, I wrote:
M = [f(x1); f(x2); f(x3)]
That didn't work - it gave me only the first outputs of every f (resulting in a 3x1 matrix). Then, I tried
M = zeros(3,2) + [f(x1); f(x2); f(x3)]
which gave me the same thing copied into two columns. Then, I typed
[M1 M2] = [f(x1); f(x2); f(x3)]
which gave me a "too many outputs" error. I tried some other variations of a similar thing in one to two lines, but nothing really worked. Of course I could fix this particular issue with some slightly longer solution (3+ lines of code) but that would be clumsy and not versatile to other dimensions. What is the simplest and most useful way around this issue?

采纳的回答

dpb
dpb 2021-10-31
The first syntax will work if the function actually returns a vector --
>> x=rand(1,5);
>> fnX=@(i)x(i:i+1);
>> fnX(1)
ans =
0.58 0.95
>> M=[fnX(1);fnX(2);fnX(3)]
M =
0.58 0.95
0.95 0.25
0.25 0.24
>> x
x =
0.58 0.95 0.25 0.24 0.71
>>
Your symptom is of your function returning two variables, not a vector.
Show us the function...

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by