Effacer les filtres
Effacer les filtres

Unable to perform assignment because the left and right sides have a different number of elements

3 vues (au cours des 30 derniers jours)
Hello,
I want to separate this char string into groups of 4 letters.
cadena='0045003e003500440045003e003500440041003f00430040004f'
r_num=num2str(zeros(length(cadena),1));
for i=1:length(cadena)
r_num(i)=cadena(i); % I create a column array which contains the components separately
end
seccion=num2str(zeros(ceil(length(cadena)/4),1));
for j=1:length(cadena)-4
seccion(j)=strcat(r_num(j),r_num(j+1),r_num(j+2),r_num(j+3)); %then I tried to join the components again in groups of four
j=j+4;
end
However, an error appeared:
Unable to perform assignment because the left and right sides have a different number of elements.
Error in Untitled4 (line 14)
seccion(j)=strcat(r_num(j),r_num(j+1),r_num(j+2),r_num(j+3));
(I also have tried to use strsplit or strtok functions, but they are for texts separated by commas)
If you find the solution, or a better way of doing it, please help me
Thanks

Réponses (1)

Ameer Hamza
Ameer Hamza le 23 Avr 2020
Modifié(e) : Ameer Hamza le 23 Avr 2020
seccion(j) is an element of a scalar array. It can only hold a single character. If you want to store multiple characters, then you should use cell arrays. Check the following code. I have also fixed a few other issues. I have also given a one-liner version of your code, which avoids all these for loops
cadena ='0045003e003500440045003e003500440041003f00430040004f';
r_num=num2str(zeros(length(cadena),1));
for i=1:length(cadena)
r_num(i)=cadena(i); % I create a column array which contains the components separately
end
seccion=cell(ceil(length(cadena)/4),1);
for j=1:4:length(cadena)
seccion{(j+3)/4}=strcat(r_num(j),r_num(j+1),r_num(j+2),r_num(j+3)); %then I tried to join the components again in groups of four
end
One-liner:
cadena ='0045003e003500440045003e003500440041003f00430040004f';
seccion = mat2cell(cadena, 1, 4*ones(1,numel(cadena)/4)).';
Access elements of cell array like this
seccion{1}
seccion{2}
..
..
seccion{end}

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by