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 comentarios

Weird Rando
Weird Rando el 9 de Mayo de 2016
Editada: Weird Rando el 9 de Mayo de 2016
Probably '\' not '/'
Walter Roberson
Walter Roberson el 9 de Mayo de 2016
No, / works for MS Windows as well as Mac and Linux, and you need to be careful if you use \ in sprintf

Iniciar sesión para comentar.

Respuestas (2)

Walter Roberson
Walter Roberson el 9 de Mayo de 2016

0 votos

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

0 votos

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 comentarios

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.
Kerst Resalk
Kerst Resalk el 10 de Mayo de 2016
I get it, thanks a lot for that explanation!

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Preguntada:

el 9 de Mayo de 2016

Comentada:

el 10 de Mayo de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by