Dawid Muserski
Dawid Muserski

Reputation: 11

varargin varargout function

I have a simple task to do in MATLAB using varargin/out for matrices.

I have to return result of multiplication elements with the same row and column number like so:

like this

tab(1,1) * tab(2,2) and so on.

I wrote some code but it only returns result for first matrix. The multiplication works because I checked using disp(result) after multiplication.

Here is my code, how should I change it to return results of all matrices?

function varargout = test(varargin)

n = length(varargin);
disp(n); 
for k=1:n
    [row, col] = size(varargin{k});
    result = 1;
    for i=1:row
        for j=1:col
            if i == j
            result = result * varargin{k}(i,i);
            end
        end
    varargout{k} = result;
    end
end

Upvotes: 1

Views: 1188

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Not an answer to your question, but your function can be re-written as one line:

function varargout = test2(varargin) 

    varargout = cellfun(@(x) prod(diag(x)), ...
                        varargin,...
                        'UniformOutput', false);

end

You can (initially) use this as a function to validate your own function, and (later) learn a lot from it by figuring out how it works.

Upvotes: 1

tmpearce
tmpearce

Reputation: 12693

The number of arguments returned will be defined by how you call the function. For example, if you wrote:

a = test(x, y, z);

only the first output argument would be returned. In contrast,

[a, b] = test(x,y,z);

would return the first and second outputs. If you want to just return a cell array with the results, name your output argument something other than varargout and you will end up with a single output, with the results of each input in a cell.

Upvotes: 0

Related Questions