将向量值函数输出分配给向量

时间:2015-06-16 21:36:01

标签: matlab

我想在f行上分配如下矢量值函数%this does not的结果。有没有办法做到这一点?

档案scratch.m

function scratch(x)
get_f(x)
end

% vector-valued function of a vector
function val = f(x)
val(1) = x(1)^3 + x(2) - 1;
val(2) = x(2)^3 - x(1) + 1;
end

function get_f(x)
%  z = f(x)  % this works
[x1,x2] = f(x);  % this does not
end

致电scratch([1,1])

>> scratch([1,1])
Error using scratch>f
Too many output arguments.

Error in scratch>get_f (line 12)
[x1,x2] = f(x);

Error in scratch (line 2)
get_f(x)

2 个答案:

答案 0 :(得分:1)

你的函数输出val是一个1x2数组,而不是2个单独的变量,所以你必须这样调用它:

arrayX = f(x);
x1 = arrayX(1);
x2 = arrayX(2);

如果你想要2个输出变量,你需要改变你的函数体:

function [y1, y2] = f(x)
    y1 = x(1)^3 + x(2) - 1;
    y2 = x(2)^3 - x(1) + 1;
end

答案 1 :(得分:0)

强制转换为单元格数组

function [x1, x2] = Untitled2(x)
    [x1, x2] = get_f(x);
end

% vector-valued function of a vector
function val = f(x)
    val(1) = x(1)^3 + x(2) - 1;
    val(2) = x(2)^3 - x(1) + 1;
end

function [x1, x2] = get_f(x)
    %  z = f(x)  % this works
    z = num2cell(f(x));
    [x1, x2] = z{:};
end