Accepting and saving multiple size matrix input

1 回表示 (過去 30 日間)
Dong-Kyeong
Dong-Kyeong 2011 年 11 月 27 日
a=[1];
b=[2 3 4];
c=[5; 6; 7];
d=[8 9 10; 11 12 13; 14 15 16];
I want to make a function that works with an undefined number of inputs.
In this case, 4 inputs (a,b,c,d)
////////////
Then I make the function as follows:
function out=Func(varargin)
Then when I use the function, I input:
result value=Func(a,b,c,d) %Only this command is allowed to get result value. The only changes that can be made are changing the number of input matrices.
////////////
Inside the function when I use the varargin, I get:
varargin(1) % [1]
varargin(2) % [1x3 double]
varargin(3) % [3x1 double]
varargin(4) % [3x3 double]
Is it possible to get the values of b,c,d instead of the matrix sizes?
I want to work with the values of b,c,d.
For example
out= sum(a) + sum(b) + sum(c) + sum(d)

採用された回答

Chandra Kurniawan
Chandra Kurniawan 2011 年 11 月 27 日
I have a function 'Func'
function out = Func(varargin)
out = 0;
for num = 1 : nargin
out = out + sum(varargin{num}(:));
end
Save the function with filename 'Func.m' And then I have a m-file
clear all; clc;
a=[1];
b=[2 3 4];
c=[5; 6; 7];
d=[8 9 10; 11 12 13; 14 15 16];
value = Func(a,b,c,d)
Then, try to run your m-file. You will get :
value =
136
>>

その他の回答 (1 件)

Junaid
Junaid 2011 年 11 月 27 日
As I understand you want a function undefined number of input. so it can either be implemented as follow.
function myFunc(varargin)
switch nargin
case{0}
% this mean no argument.
case{1}
% means one argument
case{2}
% means two argument. and so on
otherwise
% default
end

カテゴリ

Help Center および File ExchangeFourier Analysis and Filtering についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by