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

10 次查看(过去 30 天)
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(:))

回答(1 个)

Walter Roberson
Walter Roberson 2022-3-5
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{:});

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by