Home Returning a 4D array from a function in MATLAB

# Returning a 4D array from a function in MATLAB

Jonathan H
1#
Jonathan H Published in 2017-12-07 12:28:55Z
 I am trying to return a 4D array of image data from a function call in MATLAB. I'm not very advanced in MATLAB and I don't know what type of data I have to return from the function. Here is my function: function classimg = loadImages(classdir,ext) % create array of all images in directory neg = dir([classdir ext]); % get size of array (to loop through images) numFileNeg = max(size(neg)); % create a 4D array to store our images classimg = zeros(51,51,3,numFileNeg); % loop through directory for i=1:numFileNeg classimg(:,:,:,i) = imread([myDir neg(i).name]); end end  Here is the function call: negativeImgs = loadImages("C:\Users\example\Documents\TrainingImages\negatives\","*.jpg");  I cannot find any online documentation for the return type? Does anyone know what this would be? classimg is populated correctly so the code inner works.
Mike Cappello
2#
Mike Cappello Reply to 2017-12-07 19:14:18Z
 You initialize classimg to be a 51x51x3xnumFileNeg matrix of zeros. You use the zeros function, so the datatype is double. To see this clearly, call your function from the command window, and then type "whos" to see both the size and datatype of classimg.
gnovice
3#
 As Mike correctly points out, since you initialize classimg using zeros, and the default data type is double, your image data will be converted to double from whatever data type imread returns (often uint8). If you would like classimg to be the same data type as your images (which I'm assuming all have the same type), you can load one image, get its class, and initialize classimg with that specific class. Here's how you could rewrite your function: function classimg = loadImages(classdir, ext) neg = dir(fullfile(classdir, ext)); numFileNeg = numel(neg); tempImage = imread(fullfile(classdir, neg(1).name)); classimg = zeros(51, 51, 3, numFileNeg, class(tempImage)); classimg(:, :, :, 1) = tempImage; for i = 2:numFileNeg classimg(:, :, :, i) = imread(fullfile(classdir, neg(i).name)); end end  Note that I made a couple of other changes. I used fullfile instead of concatenation of the directory and file names, since it handles any issues with file separators for you. I also used numel to get the number of files as Justin suggested in a comment.