开发者

In MATLAB, how can I conveniently supply many arguments to a function?

开发者 https://www.devze.com 2023-01-29 04:01 出处:网络
I have a MATLAB function 开发者_如何学Pythonmyfun(v1,v2,v3,v4,v5,v6) and a 30x6 matrix A. The way to call the function is by passing each column of A as a separate input argument:

I have a MATLAB function 开发者_如何学Pythonmyfun(v1,v2,v3,v4,v5,v6) and a 30x6 matrix A. The way to call the function is by passing each column of A as a separate input argument:

myfun(A(:,1),A(:,2),A(:,3),A(:,4),A(:,5),A(:,6))

Just wondering whether there is a better way to do this without explicitly writing out so many times A(:,*)?


You can first place each column of A in a cell of a cell array using the function NUM2CELL, then pass the cell array contents as a comma-separated list using the {:} syntax:

B = num2cell(A,1);
myfun(B{:});


Rewrite your function to accept both conventions:

function [] = myfun(v1,v2,v3,v4,v5,v6)
    if nargin==1
        v2 = v1(:,2);
        v3 = v1(:,3);
        v4 = v1(:,4);
        v5 = v1(:,5);
        v6 = v1(:,6);
        v1 = v1(:,1);
    end

    %# use v1,v2,v3,v4,v5,v6
    %# ...
end

Now you can call as both:

myfun(A(:,1),A(:,2),A(:,3),A(:,4),A(:,5),A(:,6))
myfun(A)

Usually you would do more validation to test for the correct number of arguments...

0

精彩评论

暂无评论...
验证码 换一张
取 消