Cell2mat not working for high cell count

2 views (last 30 days)
Adel Hafri
Adel Hafri on 4 Mar 2022
Edited: Jan on 4 Mar 2022
Hello, being trying to code Run length enc/dec on Matlab, and my work worked perfectly for test matrixes, but as soon as i tried 512x512 Matrix Cell2mat started giving me this error :
Error using cat
Dimensions of arrays being concatenated are not consistent.
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
this is my code:
clear all;
%***reading a matrix x from the directory c:\
x=imread(['c:\mAT\512x512-No-Noise.jpg']);f=size(x);
c=1;
y={};
z=[];
for i=1:f(1)
y{i}=[];
for j=1:f(2)-1
if x(i,j)==x(i,j+1)
c = c + 1;
else
y{i}=[y{i} c x(i,j)];
c=1;
end
end
y{i} =[y{i} c x(i,f(2))];
c=1;
end
y
k=size(y);
z={};
for s=1:k(2)
a=size(y{1,s})
L=1;
z{s}=[];
while(L<a(2))
for n=1:y{1,s}(1,L);
z{s}=[z{s} y{1,s}(1,L+1)];
end
L = L+2;
end
end
new_z=cell2mat(z(:))
  1 Comment
Jan
Jan on 4 Mar 2022
Please use a standard indentation: ctrl-a ctrl-i in the editor. This improves the readability.

Sign in to comment.

Answers (1)

Jan
Jan on 4 Mar 2022
Edited: Jan on 4 Mar 2022
This means, that the arrays stored in the cell do not have matching sizes. Check this:
sizeZ = [cellfun('size', z(:), 1), cellfun('size', z(:), 2)];
unique(sizeZ, 'rows')
Of course this is not a problem of cell2mat . Remember that this function is used for decades by many Matlab codes. It would be extremely surprising, if you find a bug in it...
An efficient method for expanding is repelem:
k = numel(y);
z = [];
for s = 1:k
n = y{s}(1:2:end); % Every 2nd element starting from first
b = y{s}(2:2:end); % ...starting from second
z(s, :) = repelem(n, 1, b);
end
By the way, when I run your code with the test data:
x = randi([0, 255], 512, 512);
it does not cause an error.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!