whats wrong with this code?

1 回表示 (過去 30 日間)
Muazma Ali
Muazma Ali 2022 年 8 月 12 日
編集済み: Cris LaPierre 2022 年 8 月 12 日
Edit: added type statement to make code visible
Hi!
When I run similar code I get this error message saying:
type('assigning_values_to_character_arrays.m')
function assigning_values_to_character_arrays() nr_zones_analyzed=0; antall_soner=3; while nr_zones_analyzed<antall_soner % Here I actually have some functions that determines best_salt_1 and % best_salt_2 best_salt_1=input('Enter best_salt_1: ', 's'); best_salt_2=input('Enter best_salt_2: ', 's'); nr_zones_analyzed=nr_zones_analyzed +1; the_best_salt_1=string(best_salt_1); the_best_salt_1(nr_zones_analyzed)= string(best_salt_1); the_best_salt_2=string(best_salt_2); the_best_salt_2(nr_zones_analyzed)=string(best_salt_2); end for j= 1: antall_soner S1= the_best_salt_1(j); S2= the_best_salt_2(j); C{j}=sprintf('%s %s',S1,S2); end combination_of_salts=char(C{:}) end
Error using sprintf
Unable to convert 'string' value to 'char'.

回答 (2 件)

Image Analyst
Image Analyst 2022 年 8 月 12 日
I'd use character arrays instead of strings and a for loop instead of a while loop:
function assigning_values_to_character_arrays()
antall_soner = 3;
C = cell(antall_soner, 1)
for k = 1 : antall_soner
% Here I actually have some functions that determines best_salt_1 and best_salt_2
best_salt_1{k} = input('Enter best_salt_1: ', 's');
best_salt_2{k} = input('Enter best_salt_2: ', 's');
C{k} = sprintf('%s %s',best_salt_1{k}, best_salt_2{k});
end
combination_of_salts=char(C{:})
end

Cris LaPierre
Cris LaPierre 2022 年 8 月 12 日
編集済み: Cris LaPierre 2022 年 8 月 12 日
I think this error may just mean you may just need to clear your workspace before running your code. At least I was able to reproduce after turning your function into a script and running it a couple times.
I would symplify your code to the following, keeping everything as strings.
antall_soner=3;
for nr_zones_analyzed = 1:antall_soner
% Here I actually have some functions that determines best_salt_1 and
% best_salt_2
best_salt_1=input('Enter best_salt_1: ', 's');
best_salt_2=input('Enter best_salt_2: ', 's');
C(nr_zones_analyzed,1) = string(best_salt_1) + " " + string(best_salt_2);
end
combination_of_salts=C

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by