MATLAB Answers

Write a warning dialog with a dynamic number of inputs

조회 수: 4(최근 30일)
mlwermers 2021년 7월 21일
댓글: dpb 2021년 7월 21일
I would like to create a warning dialog for my script with a dynamic number of inputs to list how many folders in a scenario are empty.
For example, if I have 5 folders (folderA through folderE), and three of them are empty, the script should determine which three were empty and list them in the warning dialog such that the warning dialog says:
" The following folders are empty:
I would like this to work no matter how many folders are empty. So if only two folders are empty, only two would be listed, and if all five folders are empty, all five would be listed.
I have the list of empty folders saved in a cell array.
I initially tried running the warning message through a for loop, but it overwrote the message each time and only one folder was listed at the end.
I also tried the following code:
warningmessage = sprintf('The following folders are empty:\n%s\n',char(emptyFolders));
% empty folders is a cell array with a variable number of folder names.
warndlg = (warningmessage,'Warning');
The result from this code (for three empty folders) is a warning dialog with the message:
"The following folders are empty:
Is there a way to write a variable number of strings into a message?

채택된 답변

Walter Roberson
Walter Roberson 2021년 7월 21일
warningmessage = sprintf('The following folders are empty:\n%s\n', strjoin(emptyFolders, '\n'));
This assumes that emptyFolders is cell array of character vectors or string() array (and not 2d character array)
  댓글 수: 1
dpb 2021년 7월 21일
+1 Walter, nice application for strjoin didn't think of...

댓글을 달려면 로그인하십시오.

추가 답변(1개)

dpb 2021년 7월 21일
Two ways -- for your above with cellstr() array, just use {:} instead of char() ...
>> emptyF=cellstr("Folder"+['A':'C'].')
emptyF =
3×1 cell array
>> sprintf('%s\n',emptyF{:})
ans =
I had created as string array first and sprintf is now strings enabled...
>> emptyF="Folder"+['A':'C'].'
emptyF =
3×1 string array
>> sprintf('%s\n',emptyF)
ans =
You can, if you don't want the extra \n at the end count the size of the array and build an array-size dependent format string by
fmt=[repmat('%s\n',1,numel(emptyF)-1) '%s'];
Of course all these need to be prefixed with the fixed string to write as the first portion of the format expression...




Community Treasure Hunt

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

Start Hunting!

Translated by