Preserve spaces when using fprintf with strcat to show variables, spaces and strings on screen to user

3 ビュー (過去 30 日間)
Hi,
I have had a try at getting a string ending with a space to be preserved on screen using fprintf and strcat together but cannot preserve the spaces.
B=strcat(PR1,'.mat');
filey=B
% Y='.*2'
% if ~isempty(regexp(directory,Y))
% end
% *****************************
%%THIS PRODUCES A LIST OF ONLY THE MAT FILES
d=dir;
% d1=cellstr(d)
d1=struct2cell(d);
d2=d1(1,:);
d3=cellfun(@(x) regexp(x,'.mat'),d2,'uni',false);
d4=find(~cellfun('isempty', d3));
theMATfiles=d2(d4)'
natsort(theMATfiles)%download natsort function from file exchange
% pwd
k=1;
% for k = 1:20
% Create a mat filename, and load it into a structure called matData.
matFileName = sprintf('mat%d.mat',k);
% save(matFileName)
% load('matData.mat')
if exist(B, 'file')
A = load(filey);
fprintf(strcat('HURRAH!! File',{''},B,' does exist.\n'));
else
% fprintf('File %s does not exist.\n', matFileName);
fprintf(strcat('NOPE!! File','_',B,' does not exist.\n'));
end
I have tried placing a space e.g. {''} but it did not work, I get the following error:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in mat_ides_03 (line 53)
fprintf(strcat('HURRAH!! File',{''},B,' does exist.\n'));
  4 件のコメント
Stephen23
Stephen23 2017 年 5 月 12 日
編集済み: Stephen23 2017 年 5 月 12 日
"but it won't help me with the inserting spaces.."
I did not say that it would. I did say that natsortfiles is good for sorting filenames.
Stephen Devlin
Stephen Devlin 2017 年 5 月 17 日
Sorry if any offence was caused, it wasn't intended. I had 'natsort' in the original code already, but will take a look at natsortfiles.

サインインしてコメントする。

採用された回答

Jan
Jan 2017 年 5 月 11 日
編集済み: Jan 2017 年 5 月 11 日
C = strcat('HURRAH!! File',{''},B,' does exist.\n')
This creates a cell string. Then fprintf must fail, because it accepts strings only. Use this:
fprintf('HURRAH!! File %s does exist.\n', B);
This is safer, because the file name can contain control characters like '\n'.
Note:
natsort(theMATfiles)
is useless, because the output is not caught. Do you mean:
theMATfiles = natsort(theMATfiles);
Simplification:
d = dir;
d1=struct2cell(d);
d2=d1(1,:);
d3=cellfun(@(x) regexp(x,'.mat'),d2,'uni',false);
d4=find(~cellfun('isempty', d3));
Easier:
FileDir = dir('*.mat');
FileName = {FileDir.name};
  2 件のコメント
Stephen23
Stephen23 2017 年 5 月 11 日
編集済み: Stephen23 2021 年 4 月 18 日
And to provide the correct filename order:
S = dir('*.mat');
S = natsortfiles(S);
Stephen Devlin
Stephen Devlin 2017 年 5 月 12 日
Thanks Jan and Stephen, very much appreciated, I had missed that fprintf will only accept a string.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by