简体   繁体   中英

Nested function with two variables in matlab

I have three functions and i want two variables to run through all the functions. I tried doing this:

R = rot(mir(sca(P(1,:),P(2,:))));

however i get this error:

Error using mir (line 2)
Not enough input arguments.

Any suggestions?

%rot.m
function rot = rot(x,y)
    rot = [ cos(pi/6)*x-sin(pi/6)*y; sin(pi/6)*x+cos(pi/6)*y ];

%mir.m
function mir = mir(x,y)
    mir = [x;(-y)];

%sca.m
function sca = sca(x,y)
    sca = [2*x;2*y];

You should not be surprised about the error. Function mir expect two parameters (in fact, all of your functions expect that), but you provide only one. Mind you, a matrix is considered one parameter. You can do either of the following to correct the problem:

  1. Redefine mir to accept one parameter and split it inside the function into two separate variables

  2. Redefine sca to return two values:

     function [outx, outy] = sca(x, y) outx = 2 * x; outy = 2 * y; 

    and then pass them to mir like so:

     [scax, scay] = sca(x, y); mir(scax, scay); 

Obviously, the same needs to be done to function rot as well.

In MATLAB if you have more then one output argument you have to explicitly specify the output variables. By default function always returns one (the first) argument.

In your situation one choice can be to change definitions of your functions in such a way that they receive only one input argument as a matrix. For example:

%mir.m
function mir = mir(xy)
    mir = [xy(1,:); -xy(2,:)];

or even easier in this case (you can simplify other functions as well):

function xy = mir(xy)
    xy(2,:) = -xy(2,:);

I hope you got the idea.

Then you can run:

R = rot(mir(sca(P(1:2,:))));

If you cannot change your function definitions for some reason, you will have to split the one-line call to three function into 3 lines:

S = sca(P(1,:),P(2,:));
M = mir(S(1,:),S(2,:));
R = rot(M(1,:),M(2,:));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM