how to assign strings to a character array?

12 次查看(过去 30 天)
Hi !:)
I am trying to set the first row of my character vector or character array equal to the string best_salt_1 which changes size but firstly it is 'MgBr2',
I do it by writing the following code:
the_best_salt_1(nr_zones_analyzed)=best_salt_1;
% here nr_zone_analyzed is supposed to be the row nr of the best_salt_1. When I do this I get the error message as shown in the picture attached.

回答(1 个)

Cris LaPierre
Cris LaPierre 2022-8-12
编辑:Cris LaPierre 2022-8-12
I think you are using the terms string and char array interchangably, but they are two separate data types in MATLAB. Strings and shown with double quotes while char arrays use single quotes ("MgBr2" vs 'MgBr2'). When combining chars, you have to take into consideration their length, as each character is placed in its own column. Strings only use a single column
For this reason, my preference would be to use strings. You can convert chars to strings using the string function.
the_best_salt_1 = string(the_best_salt_1);
the_best_salt_1(nr_zones_analyzed) = string(best_salt_1);
Otherwise, you will need to take into consideration the legnth of your char, meaning your assignment must include row and column indices.
the_best_salt_1='test';
nr_zones_analyzed = 2;
best_salt_1 = 'MgBr2';
% this works
the_best_salt_1(nr_zones_analyzed,1:length(best_salt_1)) = best_salt_1
the_best_salt_1 = 2×5 char array
'test ' 'MgBr2'
% Your error
the_best_salt_1(nr_zones_analyzed+1)=best_salt_1
Unable to perform assignment because the left and right sides have a different number of elements.

类别

Help CenterFile Exchange 中查找有关 Install Products 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by