Matlab newbie - what is wrong with this function?

조회 수: 1 (최근 30일)
Alex
Alex 2013년 4월 1일
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');"

채택된 답변

Matt Kindig
Matt Kindig 2013년 4월 1일
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
Alex
Alex 2013년 4월 1일
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 2013년 4월 2일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dialog Boxes에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by