Assigning values to an array of arbitrary dimensions in MATLAB.
Show older comments
I have a problem that requires assigning values to an array of arbitrary dimensions.
For a given integer j, I pre-allocate a regular j-dimensional array such that
where
are integers for
. Such an array in MATLAB looks like:
. Such an array in MATLAB looks like:Array = NaN.*ones( repmat( d , 1 , j ) ) ;
The problem is assigning values for elements in this array. Specifically, given
are vectors of length
, I require all combinations of element-wise multiplication for each of these vectors, where each result is assigned to
.
For the simplest case
, assuming vectors
are stored in cell-arrays, I can do this quite easily using
loops:
for m = 1:d
for n = 1:d
Array( m , n ) = v{ 1 }( m ).*v{ 2 }( n ) ;
end
end
But, a "psudeo-code" implementation with j
loops would look something like:
for m( 1 ) = 1:d
...
for m( j ) = 1:d
Array( m( 1 ) , ... , m( j ) ) = v{ 1 }( m( j ) ).* ... .*v{ j }( m( j ) ) ;
end
...
end
The indexing of
now becomes variable, which I have had no success in implementing.
Does there exist a way of assigning values to an array of arbitrary dimensions in MATLAB in this manner, or perhaps a neater method?
4 Comments
dpb
on 16 Mar 2019
Sorry, I can't visualize your objective here from the above...show us a small(ish) example of the input and desired output and describe the logic in how you get to the latter from the former.
First thought that comes to mind would be sub2ind and friends, but w/o a more clear understanding of the objective couldn't tell you specific code.
Michael Ransom
on 16 Mar 2019
Walter Roberson
on 16 Mar 2019
Edited: per isakson
on 18 Mar 2019
prod(cat(2, v{:}),2)
Michael Ransom
on 16 Mar 2019
Edited: Michael Ransom
on 16 Mar 2019
Accepted Answer
More Answers (1)
Christine Tobler
on 17 Jul 2020
Using the somewhat recent implicit expansion, this can also be done without indexing into every element of the array:
function Array = value2arrayND(v)
Array = 1;
for ii=1:length(v)
% Turn d-by-1 vector into 1-by-...-by-1-by-d vector, where d is in dimension ii
viiPermuted = permute(v{ii}(:), [2:ii 1 ii+1:length(v)]);
Array = Array .* viiPermuted;
end
For the 2D case, this corresponds to
Array = v{1}(:) .* v{2}(:).'; % (d-by-1 matrix) .* (1-by-d matrix)
Categories
Find more on Logical 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!