bcf
bcf

Reputation: 2134

assign vector-valued function output to a vector

I'd like to assign the results of a vector-valued function f as below, on the %this does not line. Is there a way to do this?

file 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

call with 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)

Upvotes: 1

Views: 37

Answers (2)

user1543042
user1543042

Reputation: 3440

Force a conversion to a cell array

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

Upvotes: 0

Setsu
Setsu

Reputation: 1218

Your function output val is a 1x2 array, not 2 individual variables, so you must call it like this:

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

If you want 2 output variables instead you need to change your function body like this:

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

Upvotes: 1

Related Questions