开发者

Making outputs from an array in Matlab?

I have an array of 20 items long and I would like to make them an output so I can input it into another program.

pos = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,]

I would like to use this as inputs for another program

functio开发者_StackOverflow中文版n [lowest1, lowest2, highest1, highest2, pos(1), pos(2),... pos(20)]

I tried this and it does not work is there another way to do this?


I'm a little confused why you'd want to do that. Why would you want 20 outputs when you could just return pos as a single output containing 20 elements?

However, that said, you can use the specially named variable varargout as the last output variable, and assign a cell to it, and the elements of the cell will be expanded into outputs of the function. Here's an example:

function [lowest1, lowest2, highest1, highest2, varargout] = myfun
  % First set lowest1, lowest2, highest1, highest2, and pos here, then:
  varargout = num2cell(pos);


If what you're trying to do is re-arrange your array to pass it to another Matlab function, here it is.

As one variable:

s=unique(pos);
q=[s(1) s(2) s(end-1) s(end) pos];
otherFunction(q);

As 24 variables:

s=unique(pos); otherFunction(s(1), s(2), s(end-1), s(end), pos(1), pos(2), pos(3), pos(4), pos(5), pos(6), pos(7), pos(8), pos(9), pos(10), pos(11), pos(12), pos(13), pos(14), pos(15), pos(16), pos(17), pos(18), pos(19), pos(20));

I strongly recommend the first alternative.

Here are two examples of how to work with this single variable. You can still access all of its parts.

Example 1: Take the mean of all of its parts.

function otherFunction(varargin)
    myVar=cell2mat(varargin);
    mean(myVar)
end

Example 2: Separate the variable into its component parts. In our case creates 24 variables named 'var1' to 'var24' in your workspace.

function otherFunction(varargin)
    for i=1:nargin,
        assignin('base',['var' num2str(i)],varargin{i});
    end
end

Hope this helps.


Consider using a structure in order to return that many values from a function. Carefully chosen field names make the "return value" self declarative.

function s = sab(a,b)
  s.a = a;
  s.b = b;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜