speed up the calculation in multidimensional array

Array:RP_bin
Matrix: matrix
[~,c]=size(matrix);
xx=find(RP_bin);
q=length(xx);
[~,c]=size(matrix);
cor=zeros(c,c,q);
for i=1:q
for gg=1:c
for yy=1:c
a=matrix(1:xx(i),gg);
b=matrix(1:xx(i),yy);
cc=sum((a>0 & b>0)|(a<0 & b<0));
cc1=sum(a~=0 & b~=0);
cor(yy,gg,i)=round(100 * cc/cc1) / 100; %cc/cc1; %%array multidimension
end
end
end
>> size(cor)
ans =
82 82 188
to execution this code is :
Elapsed time is 21.425685 seconds.
is possibile to speed loop?

2 件のコメント

James Tursa
James Tursa 2023 年 7 月 14 日
Can you provide a small example of matrix and RP_bin?
aldo
aldo 2023 年 7 月 15 日
yes ..attachment it

サインインしてコメントする。

回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2023 年 7 月 15 日

1 投票

You can reduce a for loop by vectorizing the code -
load('RP_BIN.mat')
load('matlab.mat')
[~,c]=size(matrix);
xx=find(RP_bin);
q=numel(xx);
%Preallocation
[cor,COR]=deal(zeros(c,c,q));
%%Original approach
tic
for i=1:q
for gg=1:c
for yy=1:c
a=matrix(1:xx(i),gg);
b=matrix(1:xx(i),yy);
cc=sum((a>0 & b>0)|(a<0 & b<0));
cc1=sum(a~=0 & b~=0);
cor(yy,gg,i)=round(100 * cc./cc1)/100; %cc/cc1; %%array multidimension
end
end
end
toc
Elapsed time is 18.790586 seconds.
%%Modified approach
tic
gg=1:c;
for i=1:q
%As the array a is only dependent on the outer loop, bring it out of
%the inner loop, so that it isn't re-calculated in every iteration of inner loop
%thereby increasing the speed of the code
a=matrix(1:xx(i),gg);
for yy=1:c
b=matrix(1:xx(i),yy);
cc=sum((a>0 & b>0)|(a<0 & b<0),1);
cc1=sum(a~=0 & b~=0,1);
COR(yy,gg,i)=round(100 * cc./cc1)/100; %cc/cc1; %%array multidimension
end
end
toc
Elapsed time is 9.287863 seconds.
%%Comparing the output obtained
%As the calculations have NaN data, use isequaln()
isequaln(cor,COR)
ans = logical
1
As you can see that there is significant improvement in speed (more than 50%)

3 件のコメント

aldo
aldo 2023 年 7 月 15 日
Thank you but the above code makes me the correlation between 2 arrays calculated differently by the "corrcoef" function. If I calculate the original matlab function it takes me 0.3 seconds
for i=1:q
cor(:,:,i)=corrcoef(matrix(1:xx(i),:));
end
Elapsed time is 0.360681 seconds.
(0.36 vs 9.28)
there is always a lot of difference in duration
Dyuman Joshi
Dyuman Joshi 2023 年 7 月 15 日
編集済み: Dyuman Joshi 2023 年 7 月 15 日
Then why not use that only?
You asked if the loop can be sped up, I responded accordingly. You did not say that you were comparing it to an inbuilt MATLAB function.
aldo
aldo 2023 年 7 月 15 日
it is a correlation calculated in a different way and the result is different .. I am interested in the result of my code not that of matlab
anyway thanks for your code

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLinear Algebra についてさらに検索

質問済み:

2023 年 7 月 14 日

コメント済み:

2023 年 7 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by