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 commentaires

Weird Rando
Weird Rando le 9 Mai 2016
Modifié(e) : Weird Rando le 9 Mai 2016
Probably '\' not '/'
No, / works for MS Windows as well as Mac and Linux, and you need to be careful if you use \ in sprintf

Connectez-vous pour commenter.

Réponses (2)

Walter Roberson
Walter Roberson le 9 Mai 2016

0 votes

You do the sprintf and discard the result. Then you use the version with the percent in it.
Kerst Resalk
Kerst Resalk le 10 Mai 2016

0 votes

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 commentaires

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!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by