How do I load multiple .nii files in a function?

Hey everybody,
I'm struggling with loading multiple files inside a function with the 'path' as an input argument.
To make it more clear, here the part of the code that doesn't work:
function [str, crb] = TAC_str_crb(nFrames, path, dynimg)
fprintf(1, 'Reading from folder %s\n', path);
DynImg = zeros(nFrames, 340, 330, 760);
for f=1:nFrames
sprintf(dynimg, f);
filename = fullfile(path, dynimg);
fprintf(1, 'Loading %s...\n', dynimg);
fid = fopen(filename);
if(fid==-1) fprintf(2,'File not found\n');end
fseek(fid, 352, 'bof');
I = reshape(fread(fid, Inf, 'float'), 340, 330, 760);
fclose(fid);
DynImg(f,:,:,:) = I;
end
I tried to use the function like this:
TAC_str_crb(20, '/resalk/home/dyn', 'mouse1_frame%d.nii')
The problem is, that Matlab always thinks that the filename includes %d and doesn't count through all my files and therefore the fseek command doesn't work. The error message I get is:
Reading from folder /resalk/home/dyn
Loading mouse1_frame%d.nii...
File not found
Error using fseek
Invalid file identifier. Use fopen to generate a valid file identifier.
Would be great if someone could help me solve that problem.
Thanks in advance!

2 个评论

Probably '\' not '/'
No, / works for MS Windows as well as Mac and Linux, and you need to be careful if you use \ in sprintf

请先登录,再进行评论。

回答(2 个)

You do the sprintf and discard the result. Then you use the version with the percent in it.
Thanks for your answer Walter!
To be honest, I am not entirely sure what you mean. How do I discard the result of the sprintf? I'm pretty new to all that Matlab stuff, so my apologies if that question sounds kind of stupid.

2 个评论

Your line
sprintf(dynimg, f);
That calls sprintf() passing in dynimg as the first argument and f as the second argument. That creates a string result based upon the format and values. That returns the string to "ans". Then, the semi-colon tells MATLAB to throw away "ans" instead of automatically displaying it.
Change
sprintf(dynimg, f);
filename = fullfile(path, dynimg);
to
thisfile = sprintf(dynimg, f);
filename = fullfile(path, thisfile);
This stores the result of the sprintf() and passes it on to fullfile.
I get it, thanks a lot for that explanation!

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by