how to assign strings to a character array?

18 ビュー (過去 30 日間)
Muazma Ali
Muazma Ali 2022 年 8 月 12 日
編集済み: Cris LaPierre 2022 年 8 月 12 日
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 Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by