I assume that your images have the same size or size that you know in advance. That is: you do not need to scan all previous images to find out the size of the current one. If it is not, the following will not help.
The code provided will not work with parfor, because you have several employees trying to split a single file descriptor. Matlab parallel tools are designed for use with multiple clusters of computers, so things like file descriptors are not duplicated.
To make your code work with parfor, you need to open and close the file in a loop, for example:
parfor image_number=1:N fid = fopen(filename, 'r'); offset_in_bytes = npoints_per_image*element_size*(image_number-1); fseek(fid, offset_in_bytes, 'bof'); s=fread(fid, npoints_to_load,'ushort'); image=reshape(s,nrows,[]); [outputs]=foo(image); fclose(fid); end
If you find that this adds overhead to your process, you can use a nested loop and maybe some buffering:
chunk_size = ceil(N/10); parfor i = 0:9 fid = fopen(filename, 'r'); %some buffering code here %start this iteration of the parfor loop at this image_number start_num = 1+(i * chunk_size); end_num = min(N, (i+1) * chunk_size); %and end it at this one for image_number=start_num:end_num %your code here end fclose(fid); end
As already mentioned by Edrick, if you use the big advantage of vector processing in your foo function, this may not speed it up much, since parfor does the make file in single-thread mode.
source share