How can I make an array or list consisting of equally sized vectors?
1 次查看(过去 30 天)
显示 更早的评论
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)
采纳的回答
Star Strider
2014-9-9
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 个评论
Star Strider
2014-9-9
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!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!