MATLAB - Too many output arguments error need help

2.3k Views Asked by At

I don't really know how to explain what I'm after without an example. I guess the title could be better but I'm not sure how to describe the issue.

I've got the following function

function [x,y] = f(z)
z = 3;
x = z.*[2;1];
y = z.*[1 2; 3 4];
end

Now I want to use f(z) as a function handle in the next function as the input "func" and I want x and y back from f(z) to use separately in the 2nd function.

function a = h(func, b)
[x,y] = func;
b = 2;
a = b.*y;
end

But I get the following error when trying to do so

>> h(f(3),2)
Too many output arguments.

Error in h (line 2)
[x,y] = func;

How do I get x and y back separately? This doesn't seem to be working.

[x,y] = func;

I also tried:

x = func(1)
y = func(2)

but this assigns x to the first index of x and y to the 2nd index of x. How do I get it to do what I want, whilst keeping the input name as "func" and using f(z) which returns 2 outputs?

2

There are 2 best solutions below

0
On BEST ANSWER
 function a = h(func,arg, b)
 [x,y] = func(arg); % this should assign both outputs

and the call to h

 h(f,3,2) % only writing f without () will send the handle and not execute and send the result into h.

I am not able to reproduce your error. But there does exist a quite large community at mathworks site with questions and answers.


Another thing you can try if you get tired of how multiple outputs behaves is to build a cell and to return it, you can use { and } to build a cell:

function [o] = f(z)

and at the end of function f:

o = {x,y}; % writing variables in { and } separated by , builds a "cell" object.

you can learn more about cells by typing "help cell"

0
On

Here's how I'd change your example:

h(@() f(3), 2)

function [x,y] = f(z)
  x = z .* [2;1];
  y = z .* [1,2; 3,4];
end

function a = h(func, b)
  [x,y] = func();
  a = b .* y;
end

Notable points:

  • I removed the assignments to parameters z and b inside the functions. I assumed those assignments were the remnants of some experimentation.

  • What you want, if I'm not mistaken, is to partially evaluate f for z equal to 3 and then pass the resulting (anonymous) function of no arguments to h. This is done with @() f(3). The expression f(3) does not evaluate to a function handle, as noted by @mathreadler.

  • To call func in h we need a pair of parentheses, as in func(). Otherwise, we try to assign one function handle to two targets, which is an error.

The result produced by MATLAB for the code above is

$$ \begin{bmatrix} 6 & 12 \\ 18 & 24 \end{bmatrix} $$