Blue7
Blue7

Reputation: 2044

How to create an arbitrary number of variables inside a MATLAB function

In MATLAB, I have a function in which the number of variables inside varies. This is best explained with the example shown bellow.

I have a function:

Sometimes there are three input arguments and the code looks like this:

function [Y] = ffwd(X,W1,W2)

A1 = sigmf(W1*X, [1,0]);

Y = sigmf(W2*A1, [1,0]);

Sometimes there are four input arguments and the code looks like this:

function [Y] = ffwd(X,W1,W2,W3)

A1 = sigmf(W1*X, [1,0])

A2 = sigmf(W2*A1, [1,0])

Y = sigmf(W3*A2, [1,0])

Sometimes there are five input arguments and the code looks like this:

function [Y] = ffwd(X,W1,W2,W3,W4)

A1 = sigmf(W1*X, [1,0])

A2 = sigmf(W2*A1, [1,0])

A3 = sigmf(W3*A2, [1,0])

Y = sigmf(W4*A3, [1,0])

X, Y, W1, W2, W3 and so on..., are all matrices.

I need one function that will do the job of all of these, and work for any number of W's. I have tried to use the cell(dim) function to create (dim) number of variables, but it doesn't work.

This is what I have so far:

function [Y] = ffwd(X,Wcell)                  %Wcell is a cell of multiple matrices

S = size(Wcell,2);                            %this is the number of W's

A =cell(S-2,1);                               %This will create A1, A2, A3 etc

A(1) = sigmf(Wcell(1)*X, [1,0]);              %This calculates the first intermediate step  

for i=2:S-1

    A(i) = sigmf(Wcell(i)*A(i-1), [1,0]);     %This calculates all the middle intermediate steps
end

Y = sigmf(Wcell(S)*A(S-1), [1,0]);            %This calculates the last step

But it comes up with an error:

Undefined function 'mtimes' for input arguments of type 'cell'.

Error in test (line 7)
A(1) = sigmf(Wcell(1)*X, [1,0]);

Wcell(1) is a matrix, because it is the first entry in Wcell which is a cell. X is also a matrix so I do not know why this doesn't work.

I have also tried to use double(Wcell(1)), but it comes up with the error

Conversion to double from cell is not possible

How can I do this correctly?

Upvotes: 0

Views: 343

Answers (2)

Divakar
Divakar

Reputation: 221684

Assuming a simple case where X, W1, W2, etc are scalars, one can use this function -

function [Y] = ffwd(varargin)

IN = cell2mat(varargin{:});

Y = IN(1);
for k = 2:numel(IN)
    Y = sigmf(IN(k)*Y, [1,0]);
end

return;

The calling function/script would look like this -

X = 2;
IN = {[X 101 102 103 104]};
out = ffwd(IN)

Upvotes: 0

Notlikethat
Notlikethat

Reputation: 20984

Your approach is fundamentally on-track, but you have the cell array syntax incorrect and it seems unnecessarily complex. Using varargin makes things even simpler since you can then simply call with the matrices as regular arguments rather than having to construct the cell array manually:

function [Y] = ffwd(X, varargin)
Y = X;
for ii=1:length(varargin)
    Y = sigmf(varargin{ii}*Y, [1,0]);
end

Upvotes: 4

Related Questions