I wish to include or (or any) within a function where the number of arguments (logical vectors) passed in can be more than two and can vary in number. For example, the parent function may create
a=[1;0;0;0]
b=[0;1;0;0]
c=[0;0;0;1]
but the next time may add
d=[0;0;1;0]
how do I get it, in this case, to give me X=[1;1;0;1] the first time around and Y=[1;1;1;1] the second time? The number of vectors could be up to twenty so it would need to be able to recognise how many vectors are being passed in.
This is how I would do it:
function y = f(varargin)
y = any([varargin{:}], 2);
varargin
is a cell array with the function input arguments. {:}
generates a comma-separated list of those arguments, and [...]
(or horzcat
) concatenates them horizontally. So now we have a matrix with each vector in a column. Applying any
along the second dimension gives the desired result.
Since the function contains a single statement you can also define it as an anonymous function:
f = @(varargin) any([varargin{:}], 2);
Example runs:
>> f([1; 1; 0; 0], [1; 0; 0; 1])
ans =
4×1 logical array
1
1
0
1
>> f([1; 1; 0; 0], [1; 0; 0; 1], [0; 0; 1; 0])
ans =
4×1 logical array
1
1
1
1