Error : "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"

2 views (last 30 days)
I am a newbie to Matlab so forgive me if this is a redundant query.Posting here because I still can't find out how to rectify the error. I am trying to convert the decimals to their respective state vectors, on all the planes of an image and store it a matrix. The piece of code is given below.
img1 = imread('lena.jpg');
a = zeros(256,256,3);
for z = 1:3
for x=1:256
for y=1:256
m = dec2vec(img1(x,y,z),8);
a(x,y,z)= m;
end
end
end
The error am receiving is Assignment has more non-singleton rhs dimensions than non-singleton subscripts
Error in test1 (line 7)
a(x,y,z)= m;
Kindly help me out because am unable to figure out where I am going wrong.Thanks a lot.

Answers (1)

Guillaume
Guillaume on 11 Feb 2016
From the name, I'd guess that dec2vec returns a vector. a(x, y, z) is a scalar. You can't obviously squeeze a vector into a single element, hence the error you see. Possibly, you want:
a = cell(256, 256, 3) %how about giving that variable a better name, such as bitpattern?
for ...
for ...
for ...
m = ...
a{x, y, z} = m
...
To store your vectors in a cell array, or:
a = zeros(256, 256, 3, 8);
for ...
...
a(x, y, z, :) = m;
...
to store your vector in a 4D matrix.
Note that if all you want to do is convert the pixel intensities into a bit pattern, you don't need loops:
img1 = imread('lena.jpg');
bitpattern = reshape(num2cell(dec2bin(img1, 8) - '0', 2), size(img1)) %to get it as a cell array
bitpattern = reshape(permute(dec2bin(img1, 8) - '0', [1 3 4 2]), [size(img1), 8]) %to get it as a 4D array
  5 Comments
Guillaume
Guillaume on 11 Feb 2016
I have no idea what the "state vector" of a decimal, and I certainly have no idea how you get [0 0 0 0 0 1 0 0] out of (5,3).
As a I said, whatever is returned by dec2vec must have the same numbers of elements as the 4th dimension of a. And it must always be the same numbers of elements regardless of the pixel value. So, you need to change the 8 in
a = zeros(256, 256, 3, 8)
into that number of elements.
Without seeing the code for dec2vec, I can't help you any further.
Guillaume
Guillaume on 11 Feb 2016
If dec2vec is the same as this, then you need to declare a as:
a = zeros([size(img1), 256]); i.e. 256, 256, 3, 256
and your code will work.
Of course, since your image is basically telling you which index of the 3rd dimension is to be set to one for the correspond (row, column, page) coordinate, you can do this much easier with plain indexing. The 4 lines of code below are all that's needed to obtain the same result:
img = imread('lena.jpg');
statevector = zeros([size(img), 256]);
[row, col, page] = ndgrid(1:size(img, 1), 1:size(img, 2), 1:size(img, 3));
statevector(sub2ind(size(statevector), row, col, page, img+1)) = 1;

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!