How can I make an array or list consisting of equally sized vectors?

2 views (last 30 days)
I want to create an array of identical vectors, each with two componenets. I have a function that takes the cartesian product of any amount of vectors. So, seeing as I want to find the cartesian product of many vectors, I'd like to simply be able to input an array of these vectors into the function. EDIT: First off, this is the function I'm trying to use: http://www.mathworks.com/matlabcentral/fileexchange/5898-setprod For example, say I want to find the cartesian product of [1,-1] [2,4] [6,5] [8,9] but, rather than type
setprod([1,-1] [2,4] [6,5] [8,9])
I want to put the vectors in an array first, then input that array into the function.
So:
a = ([1,-1] [2,4] [6,5] [8,9])
setprod(a)
The only issue is, I don't know how to save the vectors in an array such that the function can read them each as separate vectors. (In my actual program I have too many arrays to write out)

Accepted Answer

Star Strider
Star Strider on 9 Sep 2014
Use a cell array:
f = @(a,b,c,d) [a b c d];
a = 3; b = 5; c = 7; d = 13;
args = num2cell( [ a b c d ] );
fa = f(args{:})
This is only an illustration, but you can likely adapt it to your situation.
  2 Comments
Daniel
Daniel on 9 Sep 2014
Edited: Daniel on 9 Sep 2014
What here is the cell array? Can you add some comments or a short explanation please?
Star Strider
Star Strider on 9 Sep 2014
Sure!
The ‘f’ anonymous function is simply created to illustrate the idea.
The cell array is created by num2cell in the ‘args’ assignment. You could also do the ‘args’ assignment as:
args = {a b c d};
although if you have an array, passing arguments to num2cell is probably easiest. Your call as to what’s best in your application.
In the ‘fa’ assignment (that calls ‘f’), args{:} distributes the elements of its cell array across the argument list of ‘f’, as illustrated by this line:
[q1 q2 q3 q4] = args{:}
that produces:
q1 =
3
q2 =
5
q3 =
7
q4 =
13
It’s just the magic of cell arrays!

Sign in to comment.

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!