I try to assign values for the first 2 dimensions of a 2D array, while keeping the third dimension fixed. But I am getting an error.
Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts
See the code snippet below (Note that I use allcomb() from here ).
Any idea why and how to fix?
A = zeros(2, 94, 10);
combs = allcomb(1:2,1:94);
A(combs(:,1), combs(:,2), 1) = 1:(2*94);
Note that my intention was to write a vectorized form of:
A = zeros(2, 94, 10);
combs = allcomb(1:2,1:94)
vals = 1:(2*94);
for k=1:length(vals)
A(combs(k,1), combs(k,2), 1) = vals(k);
end
The rhs
, right hand side, of the equation needs to have the same dimensionality as the lhs
. in this case, you're trying to assign an N x 1
vector to an 2 x N x 1
array.
Try,
A = zeros(2, 94, 10);
combs = allcomb(1:2,1:94);
val = (1:2*94)';
A(combs(:,1), combs(:, 2), 1) = [val, val];
Good luck!
You can try something like this:
A = zeros(2, 94, 10);
B = A;
combs = allcomb(1:2, 1:94);
vals = 1:(2*94);
for k=1:length(vals)
A(combs(k, 1), combs(k, 2), 1) = vals(k);
end
% here it starts
val = repmat(1:94, 94, 2);
B(combs(:, 1), combs(:, 2), 1) = [val; val + 94];
isequal(A, B) % returns 1
This should give you the desired result.
I found the short and elegant implementation I was looking for, using sparse() initialization:
A = zeros(2, 94, 10);
combs = allcomb(1:2,1:94);
vals = 1:(2*94);
%% Here it is:
A(:,:,1) = sparse(combs(:,1), combs(:,2), vals);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.