how to assign strings to a character array?

16 views (last 30 days)
Muazma Ali
Muazma Ali on 12 Aug 2022
Edited: Cris LaPierre on 12 Aug 2022
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.

Answers (1)

Cris LaPierre
Cris LaPierre on 12 Aug 2022
Edited: Cris LaPierre on 12 Aug 2022
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.

Categories

Find more on Install Products in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!