Matlab newbie - what is wrong with this function?

1 Ansicht (letzte 30 Tage)
Alex
Alex am 1 Apr. 2013
I am trying to open multiple data files at once and store them in a single array. When I use the 'Multiselect' option from uigetfile I get an error with fopen which I don't get when I only select a single file. I am hoping someone can tell me how to properly use fopen in this situation and I am trying to avoid individually selecting each file. DO I need a for loop or something? Here is my function (starting after "end"):
if true
% code
end
[FileName,PathName] = uigetfile('\\PDNAS02\Home\My Documents\qual lum stability\032113\*.lum', 'MultiSelect', 'on', 'Select an LUM File...\n');
file = strcat(PathName,FileName)
fild = fopen(file,'r');
img = fread(fild,[1392,1040],'float32');
img = rot90(flipdim(img,2));
and here is the error it shows me after trying to execute it selecting multiple files at the uigetfile step
"Error using fopen First input must be a file name of type char, or a file identifier of type double.
Error in read_LUM_all (line 16) fild = fopen(file,'r');"

Akzeptierte Antwort

Matt Kindig
Matt Kindig am 1 Apr. 2013
When you select multiple files, the output in Filename is a cell array, not a string, so it won't work in strcat the way you expect. You need to for() loop through the entries to read each file separately.
Also, use fullfile() to combine pathnames and filenames. It is more robust than the strcat method you have shown.
Something like:
for k=1:length(Filename),
file = fullfile(PathName, Filename{k});
fild = fopen(file,'r');
.....
end
  2 Kommentare
Alex
Alex am 1 Apr. 2013
Thank you that worked! the only problem is that, if I open N number of file I need my 'img' array to be a 3D array of size 1040x1392xN so that I can reference each individual file by img(:,:,1) for example. I used your solution and came up with this:
for i=1:length(FileName)
file = strcat(PathName,FileName{i})
fild = fopen(file,'r');
img = fread(fild,[1392,1040],'float32');
img = rot90(flipdim(img,2));
end
which gave me an array called img of size (1040x1392 double). Is there a way to keep it as a 3D array?
Matt Kindig
Matt Kindig am 2 Apr. 2013
Sure, just modify your code to define img as 3D.
N=length(Filename);
img = NaN(1392, 1040, N);
for i=1:length(FileName)
file = strcat(PathName,FileName{i})
fild = fopen(file,'r');
IM = fread(fild,[1392,1040],'float32');
img(:,:,i) = rot90(flipdim(IM,2));
end
Note also that I pre-allocated img (i.e., defined it to have the full size). Such memory allocation improves performance.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Dialog Boxes finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by