MATLAB: Optimize a code

hue to tempmatrix to columnoptimize code

Hello,
I attach here a piece of code which I think works quite slow because some variables are called, written and recalled…this just wastes lot of time. I'm new, but I think that someone might help.
As you can read, the quantities hue, inten and sat are used, but saved as matrix, whereas I need them as column vector to be used, so I need to convert the matrix to column vector by writing on a file, then read from the file those values and re-write on a file the same quantity plus the temperature.
Please, do not hesitate to ask me question if you ahve any or to point out some manner to mak the code working faster and nicer.
Kind regards, Antonio
%input image###.bmp, cal.txt (calibration file)
%output out_hue2temp.dat (tecplot file of temperature)
clear all
close all
X0 =1
Y0 =1
H = 492
W = 658
%W = 290
%H = 56
%X0 = 162
%Y0 = 81
%save as matrix variables the hue, inten and sat of the picture
name = '28.60';
ifile = strcat( name,'.bmp');
x = imread( ifile, 'BMP' );
x = x(Y0:Y0+H-1,X0:X0+W-1,:);
y = RGB2HSV(x);
hue = y(:,:,1)* 255;
inten = y(:,:,3)* 255;
sat = y(:,:,2)*255;
figure;imshow(x)
%%%%%%write initial HUE or INTENSITY %%%%%%%
%This writing to file is useful so that I transoform hue, inten and sat from matrix to vector of one column
ofile = strcat( 'totHUE.dat');
fid = fopen(ofile,'w');
for ii = 1:H
for j = 1:W
fprintf(fid, '%6.2f %6.2f %3.1f %3.1f %3.1f \n',ii,j,hue(ii,j),inten(ii,j),sat(ii,j));
end
end
fclose(fid);
datawh=[W,H]
save data.dat datawh -ascii
%I take the columns of inten, sat and hue from the file
load calHUE.dat
load totHUE.dat
hue=totHUE;
x=totHUE(:,1);
y=totHUE(:,2);
z=totHUE(:,3);
v=totHUE(:,4);
w=totHUE(:,5);
%plot(cal(:,1),cal(:,2))
temp=x;
temp(:)=0;
for ii = 1:length(x(:,1))
temp(ii)=interp1(calHUE(:,1), calHUE(:,2), z(ii),'nearest');
end
% Resave on a file the values of before and temperature
load data.dat
W=data(1);
H=data(2);
ofile2 = strcat('out_hue2temp.dat');
fid2 = fopen(ofile2,'w');
fprintf(fid2,'VARIABLE="X","Y","TEMP","HUE","INTEN","SAT",',W,H)
fprintf(fid2,'\n zone i=%d j=%d\n',W,H)
for ii = 1:length(x(:,1))
fprintf(fid2,'%6.2f %6.2f %3.1f %3.1f %3.1f %3.1f \n',x(ii),y(ii),temp(ii),z(ii),v(ii),w(ii));
end

Best Answer

A couple comments
1. I would use the Profiler to see where your code is going slow: http://www.mathworks.com/help/techdoc/ref/profile.html
2. You should not need to write out to a file just to reshape a matrix to a column vector. Try the reshape function: http://www.mathworks.com/help/techdoc/ref/reshape.html