How to assign new variables?

I am using following lines of matlab code to assign new variables to print on plot.
if(dependent_vars{jj} == 'act_y_ha')
par = 'act\_y\_ha'
end
if(dependent_vars{jj} == 'act_per_ha')
par = 'act\_per\_ha'
end
This code is giving following error
par = 'act\_y\_ha'
Arrays have incompatible sizes for this operation.
Error in ds_reg (line 69)
if(dependent_vars{jj} == 'act_per_ha')
I request you to kindly suggest me to fix the error.
Devendra

 Respuesta aceptada

Konstantinos
Konstantinos el 13 de Abr. de 2024

0 votos

The error you're encountering, "Arrays have incompatible sizes for this operation," suggests that the comparison operation == between the string 'act_per_ha' and the cell array element dependent_vars{jj} is causing an issue due to incompatible sizes or types.
To fix this error, you can use the strcmp function to compare strings in MATLAB. Here's the corrected code:
if strcmp(dependent_vars{jj}, 'act_y_ha')
par = 'act\_y\_ha';
end
if strcmp(dependent_vars{jj}, 'act_per_ha')
par = 'act\_per\_ha';
end

6 comentarios

Devendra
Devendra el 13 de Abr. de 2024
Thank you very much for your kind help. However, following error has occured;
Error using strcmp
Not enough input arguments.
Error in ds_reg (line 66)
if strcmp(dependent_vars{jj} == 'act_y_ha');
Please suggest me how to assign new variables?
Deva
>>
Voss
Voss el 13 de Abr. de 2024
Editada: Voss el 13 de Abr. de 2024
It's
strcmp(dependent_vars{jj}, 'act_y_ha')
not
strcmp(dependent_vars{jj} == 'act_y_ha')
Devendra
Devendra el 13 de Abr. de 2024
Thanks a lot for your kind help, Deva
Voss
Voss el 13 de Abr. de 2024
@Devendra: You're welcome!
Note that an easy way to prepend a backslash to all underscores in all elements of dependent_vars is:
dependent_vars = strrep(dependent_vars,'_','\_');
Devendra
Devendra el 13 de Abr. de 2024
Thank you very much for your help, Devendra
Star Strider
Star Strider el 13 de Abr. de 2024
@Devendra — See: Answer

Iniciar sesión para comentar.

Más respuestas (1)

Star Strider
Star Strider el 13 de Abr. de 2024
Use the strrep function instead of the if block —
jj = 1;
dependent_vars{jj} = 'act_per_ha';
jj = 2;
dependent_vars{jj} = 'act_per_ha';
jj = 3;
dependent_vars{jj} = 'line with no underscores';
for jj = 1:numel(dependent_vars)
dependent_vars{jj} = strrep(dependent_vars{jj}, '_', '\_');
end
dependent_vars{:}
ans = 'act\_per\_ha'
ans = 'act\_per\_ha'
ans = 'line with no underscores'
.

2 comentarios

Devendra
Devendra el 14 de Abr. de 2024
Thank you for your help. Deva
Star Strider
Star Strider el 14 de Abr. de 2024
My pleasure!

Iniciar sesión para comentar.

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Preguntada:

el 13 de Abr. de 2024

Editada:

el 14 de Abr. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by