Possibly incorrect Matlab error: "Subscripted assignment dimension mismatch" - matlab

Matlab is giving me the error, "Subscripted assignment dimension mismatch" however I don't think there should be an issue. The code is below but basically I have a temp matrix that mimics the dimensions of another matrix, testData (actually a subset of it). I can assign the output of imread to the temp matrix but not to a subset of testData that has the same dimensions. I can even use the size function to prove they are the same dimensions yet one works and one doesn't. So I set temp = imread and then testData = temp and it works. But why should I have to do that?
fileNames = dir('Testing\*.pgm');
numFiles = size(fileNames, 1);
testData = zeros(32257, numFiles);
temp = zeros(32256, 1);
for i = 1 : numFiles,
fileName = fileNames(i).name;
% Extracts some info from the file's name and stores it in the first row
testData(1, i) = str2double(fileName(6:7));
% Here temp has the same dimensions as testData(2:end, i)
% yet testData(2:end, i) = imread(fileName) doesn't work
% however it works if I use temp as a "middleman" variable
temp(:) = imread(fileName);
testData(2:end, i) = temp(:);
end

If the file that you're reading is a color image, imread returns an MxNx3 array. You can't assign a 3D array to a 1D vector without reshaping it, even if it contains the same number of elements. That's probably why you get the error when you try to assign the output of imread directly to testData. However, when you use an intermediate variable and collapse it into a column vector, the assignment works because now you're assigning a 1D vector to another 1D vector of equal size.
If you don't want to use an additional step, try this
testData(2:end,i)=reshape(imread(fileName),32256,1);

Related

Storing image data as a row vector

I have multiple images in a folder, and for each image, I want to store the data(pixel values) as a row vector. After I store them in a row vector I can combine these row vectors as one multi dimensional array. e.g. the data for the first image will be stored in row 1, the data for the second image will be stored in row 2 and so on. And any time I want to access a particular image data, let us say I want the third image, I can do something like this race(3,:).
I am currently getting the error:
Dimensions of matrices being concatenated are not consistent.
The error occurs here race = [race; imagevec] I am lost in how to correct this, unless imagevec = I(:)' is not converting the matrix to a row vector .
race = []; % to store all row vector
imagevec = []; % to store row vector
path = 'C:\Users\User_\somedir\'; % directory
pathfile = dir('C:\Users\User_\somedir\*.jpg'); % image file extension in directory
for i = 1 : length(path)
filename = strcat(path,pathfile(i).name); % get the file
I = imread(filename); % read file
imagevec = I(:)'; % convert image data to row vector
race = [race; imagevec]; % store row vector in matrix
end
Using a cell array instead of a matrix will allow you to index in this way even if your images are of different sizes.
You don't even have to turn them into a row vector to store them all in the same structure. You can do something like this:
path = 'C:\Users\User_\somedir\'; % directory
pathfile = dir([path,*.jpg']); % image file extension in directory
race = cell(length(pathfile),1);
for i = 1 : length(pathfile)
filename = strcat(path,pathfile(i).name); % get the file
I = imread(filename); % read file
race{i} = I; % store in cell array
end
Then when you want to perform some operation, you can simply index into the cell array. You could even turn it into a row vector, if you wanted to, as follows.
thisImage = race{3}(:)';
If you are using a matrix to store the results, all rows of a matrix must be the same length.
Cell arrays are similar to arrays except the elements need not be the same type / size.
You can accomplish what you are looking for using a cell array. First, initialize race to:
race = {};
Then try:
race = {race{:}, imagevec};

Locate the indexes of rows in Matlab

I have stored in a struct file in matlab a database and the correspondant label files. In order to read my database matrix from the struct into a matrix I am using the following matlab command:
train_data_matrix = (cat(1, train_data.f2));
The size of the train_data struct is 883. However since there are some empty samples in the end the size of the train_data_matrix is 833. My problem is that I have annotation for all the samples. Thereby the size of the annotation is 883x1 How can I remove from the annotation vector the rows that are empty in the database matrix?
You can use isempty to check for missing values and remove them
% Store data in a cell array (preserves missing values)
tmp = {train_data.f2};
% Create a logical array that is TRUE where the missing values are
toremove = cellfun(#isempty, tmp);
% Convert to an array (removes missing values as you've mentioned)
data = cat(1, tmp{:});
% Create an array of annotations (after removing the ones that are missing data)
annotations = cat(1, train_data(~toremove).annotations);

Adding size information of dataset to file name

I have several datasets, called '51.raw' '52.raw'... until '69.raw' and after I run these datasets in my code the size of these datasets changes from 375x91x223 to sizes with varying y-dimensions (i.e. '51.raw' output: 375x45x223; '52.raw' output: 375x50x223, ... different with each dataset).
I want to later save the '.raw' file name with this information (i.e. '51_375x45x223.raw') and also want to use the new dataset size to later reshape the dataset within my code. I have attempted to do this but need help:
for k=51:69
data=reshape(data,[375 91 223]); % from earlier in the code after importing data
% then executes code with dimensions of 'data' chaging to 375x45x223, ...
length=size(data); dimensions.([num2str(k)]) = length; %save size in 'dimensions'.
path=['C:\Example\'];
name= sprintf('%d.raw',k);
write([path name], data);
% 'write' is a function to save the dat in specified path and name (value of k). I don't know how to add the size of the dataset to the name.
Also later I want to reshape the dataset 'data' for this iteration and do a reshape with the new y dimensions value.
i.e. data=reshape(data,[375 new y-dimension 223]);
Your help will be appreciated. Thanks.
You can easily convert your dimensions to a string which will be saved as a file.
% Create a string of the form: dim1xdim2xdim3x...
dims = num2cell(size(data));
dimstr = sprintf('%dx', dims{:});
dimstr = dimstr(1:end-1);
% Append this to your "normal" filename
folder = 'C:\Example\';
filename = fullfile(folder, sprintf('%d_%s.raw', k, dimstr));
write(filename, data);
That being said, it is far better include this dimension information within the file itself rather than relying on the filename.
As a side note, avoid using names of internal functions as variable names such as length, and path. This can potentially result in strange and unexpected behavior in the future.
Update
If you need to parse the filename, you could use textscan to do that:
filename = '1_2x3x4.raw';
ndims = sum(filename == 'x') + 1;
fspec = repmat('%dx', [1 ndims]);
parts = textscan(filename, ['%d_', fspec(1:end-1)]);
% Then load your data
% Now reshape it based on the filename
data = reshape(data, parts{2:end});

In an assignment A(I) = B, the number of elements in B and I must be the same

This is my code in Matlab: How could I get all values of all 5 images saved? This code only returns the last image! I tried using IM(l) but it gives me an error: In an assignment A(I) = B, the number of elements in B and I must be the same.
Amount_measurements = 5;
IM=zeros(2097152,1);
l=1;
for l=(1:Amount_measurements)
if l < 9
%index = double(0)+double(0)+double(l+1);
index = strcat(num2str(double(0)),num2str(double(0)),num2str(double(l+1)));
elseif l < 99
index = double(0)+double(l+1);
else
index = double(l+1);
end
file_name1='trial.nii.gz';
%disp(file_name1);
jesu=load_nii(file_name1);
[x,y,z] = meshgrid(1:256,1:256,1:256);
[lx,ly,lz] = meshgrid(1:2:256,1:2:256,1:2:256);
newImage = interp3(x,y,z,jesu.img,lx,ly,lz);
IM= newImage(:);
end
I want the values newImage(:) to be stored as IM1=newImage(:) IM2=newImage(:) IM3=newImage(:) IM4=newImage(:) so on... How could I go about with it?
Since you mentioned wanting a variable-length version of IM1=newImage(:) IM2=newImage(:) IM3=newImage(:) IM4=newImage(:), you're looking for a cell array. Try
IM{l} = newImage;
instead of
IM(l) = newImage(:);
The important difference is the use of braces rather than parentheses. Use a right-hand side ofnewImage(:) if you want to reshape into a vector, just newImage if you want to preserve it as a matrix.
By using IM(l) you're trying to add an entire column vector (newImage(:)) to a single element (the l-th element) in the array IM, that's why Matlab throws the error.
You should consider concatenation: since newImage(:) is a column-vector, replace
IM= newImage(:);
with
IM=[IM newImage(:)];
but at the top of the script you should also initialize IM as
IM=[];
At the end of the loop, the resulting IM will have Amount_measurements columns where 1 column = 1 newImage(:).
Note #1: this will only work if newImage(:) always has the same length.
Note #2: if you know a priori how long the vector newImage(:) is and, again, by assuming that its length never changes, you should consider preallocating the IM matrix by replacing IM=[]; with IM=zeros(X,Amount_measurements); where X is the number of elements in newImage(:). Finally, regarding the concatenation stage, you should replace IM=[IM newImage(:)]; with IM(:,l)=newImage(:).
Note #3: as instead, if the size of newImage(:) can change you cannot rely on preallocation and matrices, but you must use cell arrays: the last instruction in your loop should be IM{l}=newImage(:);.

Extract values from vector and save in new vector

I have a vector Cycle() that can contain several elements with a variable size.
I want to extract from this vector all the values which are in the odd columns, i.e. Cycle(1), Cycle(3), Cycle(5) ... and save them into a new vector Rcycle.
That's my code:
Rcycle = zeros(1, length(cycle)/2);
Rcycle(1) = cycle(1);
for j=3:length(cycle);
for i=2:length(Rcycle);
Rcycle(i) = cycle(j);
j = j+2;
end
end
Also I want to extract from Cycle() the even columns and save them in a vector Lcycle. My code:
Lcycle = zeros(1, length(cycle)/2);
Lcycle(1) = cycle(2);
for k=4:length(cycle);
for i=2:length(cycle);
Lcycle(i) = cycle(k);
k = k+2;
end
end
By running this for a sample Cycle() with 12 elements I get the right results for Lcycle, but the wrong ones for Rcycle. Also I get the error that my matrix have exceeded its dimension.
Has anyone any idea how to solve this in a more smooth way?
Use vector indexing!
Rcyle=cycle(1:2:end); %// Take from cycle starting from 1, each 2, until the end
Lcycle=cycle(2:2:end);%// same, but start at 2.