Make my code for taking norm efficient

4 views (last 30 days)
here is my code that is taking norm between 2 rows from 2 different excel files,it picks one row from my_first_file.xlsx and take norm with all the rows in my_second_file.xlsx and and store all the values to R i.e array/ vector and after completing one inner loop it takes the minimum value and its index from the array R,it runs OK but it takes lot much time to execute,please amend it in such a way that it takes considerably less time and performs efficiently and correct me where i am wrong,you are welcome.
n=853;m=500;
for s=1:n % n=number of rows in my_first_file.xlsx
filename = 'my_first_file.xlsx';
row1 = xlsread(filename,strcat('E',num2str(s),':EB',num2str(s)));
for i=1:m % m=number of rows in my_second_file.xlsx
filename1 = 'my_second_file.xlsx';
row2 = xlsread(filename1, strcat('A',num2str(i),':DX',num2str(i)));
sqE=norm(row2-row1);
R(i) = sqE;
end
[Val Ind] = min(R);
ran=sprintf('%c%d','A',s);
xlswrite(Hello, [Val, Ind],resultsheet,ran);
end

Accepted Answer

Mischa Kim
Mischa Kim on 8 Sep 2014
Edited: Mischa Kim on 8 Sep 2014
Muahmmad, why don't you read in all data from the Excels files at once (in other words you are only calling xlsread twice) and save the data in matrices? If available (Parallel Computing Toolbox, that is), use parfor instead of a for-loop.
  3 Comments
Mischa Kim
Mischa Kim on 8 Sep 2014
Use something like
mat1 = xlsread('ex1.xlsx'); % define the range for your files appropriately
mat2 = xlsread('ex2.xlsx'); % define the range for your files appropriately
for ii = 1:size(mat1,1)
for jj = 1:size(mat2,1)
norm_12(jj + (ii-1)*size(mat2,1)) = norm(mat1(ii,:)-mat2(jj,:));
end
end
Muhammad Usman
Muhammad Usman on 8 Sep 2014
I draw some results using my code,and then i try your above code i got different values please explain me if u can that what does this means
norm_12(jj + (ii-1)*size(mat2,1))

Sign in to comment.

More Answers (1)

Joseph Cheng
Joseph Cheng on 8 Sep 2014
before the for loop read all the data from row 1 to row m from my_second_file.xlsx into matlab and then reference that data in the loop. it should reduce the time from opening and reading from the excel file in each for loop.
  2 Comments
Muhammad Usman
Muhammad Usman on 8 Sep 2014
let me know how do i reference... Thanks
Joseph Cheng
Joseph Cheng on 8 Sep 2014
you basically did so before. just as you're reading in one line at a time. read in the whole thing like Mischa Kim described. so instead of reading in each row read in the whole block
XLS1= xlsread(filename,strcat('E',num2str(1),':EB',num2str(n)));
XLS2 = xlsread(filename1, strcat('A',num2str(1),':DX',num2str(m)));
Then you you can reference them like any 2D array in matlab.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!