How to transform a cell of Different size arrays into a matrix

15 views (last 30 days)
Hello, being trying to implemnt a Run length encoder/decoder in matlab, and i have being having an issue in my code where cell2mat gives me this error with some Images
Error using cat
Dimensions of arrays being concatenated are not
consistent.
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
at a closer inspection i realized that the encoded cell arrays of the images that give the error are not the same size, so im wondering if there is a way to circumvent that
here is my code:
clear all;
%***reading a matrix x from the directory c:\
[x,map]=imread(['c:\mAT\12m.tif']);
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(:))

Answers (1)

Walter Roberson
Walter Roberson on 5 Mar 2022
at a closer inspection i realized that the encoded cell arrays of the images that give the error are not the same size, so im wondering if there is a way to circumvent that
No, there is no way around that. You are trying to produce a 2D numeric array based on elements that are different sizes. MATLAB does not support irregular numeric arrays. MATLAB will never support irregular numeric arrays.
The closest you can get is if you pad short rows.
maxlen = max(cellfun(@length, z));
z = cellfun(@(V) [V, nan(1, maxlen-length(V))], z, 'uniform', 0);
new_z = vertcat(z{:});

Categories

Find more on Cell Arrays 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!