I need to insert a changing string into an input statement

12 ビュー (過去 30 日間)
Kevin Hurley
Kevin Hurley 2022 年 7 月 13 日
回答済み: Walter Roberson 2022 年 7 月 13 日
I am trying to iterate through all of the days of the week so that the input statement asks for 'Did the employee work on Monday of week 1' and then Tuesday and then Wednesday etc but sprintf and fprintf both dont work. Is there a funciton that allows you to put cells in a statement like that?
days = 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday';
days = split(days);
for weeknum = 1:2
for daynum = 1:7
letter = input(sprintf('Did the employee work on %d of week %d (y/n): ',days(daynum),weeknum),'s');

採用された回答

Walter Roberson
Walter Roberson 2022 年 7 月 13 日
You were quite close, but you missed an indexing and got a format wrong
days = 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday';
days = split(days);
for weeknum = 1:2
for daynum = 1:7
letter = input(sprintf('Did the employee work on %s of week %d (y/n): ', days{daynum}, weeknum),'s');
%stuff
end
end
But I would suggest
days = ["Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"];
for weeknum = 1:2
for daynum = 1:length(days)
prompt = "Did the employee work on " + days(daynum) + " of week " + weeknum + " (y/n): ";
letter = input(prompt, 's');
%stuff
end
end

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 7 月 13 日
fprintf("You should use %%d to print integer values like: %d\n", 3)
You should use %d to print integer values like: 3
fprintf("You should use %%s to print text like: %s\n", "hello")
You should use %s to print text like: hello
fprintf("Using %%s to print integer values may not do what you expect: %s\n", 65)
Using %s to print integer values may not do what you expect: A
fprintf("Using %%d to print text data also may not do what you expect: %d\n", 'hello')
Using %d to print text data also may not do what you expect: 104 Using %d to print text data also may not do what you expect: 101 Using %d to print text data also may not do what you expect: 108 Using %d to print text data also may not do what you expect: 108 Using %d to print text data also may not do what you expect: 111
char(65)
ans = 'A'
double('hello')
ans = 1×5
104 101 108 108 111

カテゴリ

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