MATLAB Answers

Write a warning dialog with a dynamic number of inputs

조회 수: 4(최근 30일)
mlwermers
mlwermers 2021년 7월 21일
댓글: dpb 2021년 7월 21일
Hello!
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:
folderA
folderC
folderD"
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:
fffooollldddeeerrrACD"
Is there a way to write a variable number of strings into a message?
Thanks!

채택된 답변

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
dpb 2021년 7월 21일
+1 Walter, nice application for strjoin didn't think of...

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

추가 답변(1개)

dpb
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
{'FolderA'}
{'FolderB'}
{'FolderC'}
>>
>> sprintf('%s\n',emptyF{:})
ans =
'FolderA
FolderB
FolderC
'
>>
I had created as string array first and sprintf is now strings enabled...
>> emptyF="Folder"+['A':'C'].'
emptyF =
3×1 string array
"FolderA"
"FolderB"
"FolderC"
>> sprintf('%s\n',emptyF)
ans =
'FolderA
FolderB
FolderC
'
>>
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...

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by