6

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.

tk421
  • 5,775
  • 6
  • 23
  • 34
Mary
  • 788
  • 6
  • 19
  • 43

2 Answers2

9

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
2

I'm sure you already thought of this:

a=[1;0;0;0]
b=[0;1;0;0]
c=[0;0;0;1]
a|b|c % returns [1;1;0;1]

However there is a much simpler answer to this:

any([a,b,c,d],2);

easily extendable by just concatinating the variables as above, before inputting it into the anyfunction. If you want to put it into a function here's way to do it:

function customOr(varargin)
  any(cell2mat(varargin),2) % equivalent to any([varargin{:}],2);
end
customOr(a,b,c) % returns [1;1;0;1]
customOr(a,b,c,d) % returns [1;1;1;1]
user2305193
  • 2,079
  • 18
  • 39