MATLAB: How to take the mean of hyperspectral image of size (1312*959*31) and plot its spectrum in matlab 7.0 after masking the specific part

hyperspectral imageImage Processing Toolboxmeanplot

S=load('Daylight_Scene_06.mat');
image1=S.tensor;
image1=S.tensor(:,:,1); %S.tensor(:,:,k) k wavelengths

imshow(image1);
%BW=roipoly;

BW = roipoly(image1);
r=zeros(1312,959);
for i=1:1312;
for j=1:959;
if BW(i,j)==1
r(i,j)=image1(i,j);
%r2(i,j)=image2(i,j);

end
end
end
imshow(r);
image2=S.tensor;
image2=S.tensor(:,:,2); %S.tensor(:,:,k) k wavelengths
imshow(image2);
%BW=roipoly;
BW = roipoly(image2);
r1=zeros(1312,959);
for i=1:1312;
for j=1:959;
if BW(i,j)==1
r1(i,j)=image2(i,j);
%r2(i,j)=image2(i,j);
end
end
end
imshow(r1);

Best Answer

Learn to use matrix operations instead of loops. Your code will be a lot faster and much easier to read. For example, your first loop and the declaration of r can be replaced by just this one line:
r = image2 .* (BW == 1);
%and if BW is just 0 and 1, then:

% r = image2 .* BW;
The same can be applied all at once to your hyperspectral image with:
maskedimage = bsxfun(@times, S.tensor, BW == 1);
%and if BW is just 0 and 1, then:
%maskedimage = bsxfun(@times, S.tensor, BW);
To average all the images into one:
meanmaskedimage = mean(maskedimage, 3); %average hyperspectral image along the 3rd dimension