# How to speed up the following Matlab script? Can anyone suggest me to speed up the process?

3 views (last 30 days)
SA on 9 May 2021
Commented: SA on 13 May 2021
In the following scripts, I get expected result but the process is very slow. Is there any other way to make the execution faster/fastest ?
clc; close all; clear all;
load Array.mat; % B is the name
per_group = 1000;
[row,col]=size(B); % val would be a matrix of size (C*C)
limit=row/per_group;
value=cell(1,limit);
count=0;
val = zeros(col); % Memory Pre-allocation
for kk = 1:per_group:row
count=count+1;
group_end = min(row, kk+per_group-1);
for jj= 1:col
f1 = A(kk:group_end,jj);
for i=(jj+1):col
f2= A(kk:group_end,i);
[Pyy,freq]=cpsd(f2,f2,hanning(512),[],512,500);
[Pxy,freq]=cpsd(f1,f2,hanning(512),[],512,500);
[Pxx,freq]=cpsd(f1,f1,hanning(512),[],512,500);
coh=(Pxy)./sqrt(Pxx.*Pyy);
realCoh=real(coh(42));
val(jj,i)=realCoh;
end
end
value{count}=val+val'+eye(col)
end

dpb on 9 May 2021
Edited: dpb on 9 May 2021
Since you're doing all the work only to return coherence, look at
doc mscohere
to return the coherence directly with all the intermediares buried in the call instead of separate.
Alternatively, you could use the array syntax of cpsd and pass arrays instead of three calls with vectors--
...
[P,freq]=cpsd([f1 f2 f1],[f1 f2 f2],hanning(512),[],512,500);
coh=P(:,3)./sqrt(P(:,1).*P(:,2));
realCoh=real(coh(42));
The burying of "magic numbers" in code makes things hard to change/debug; if that number would change, you have to change the code and find all occurrences to ensure everything changes together. If it were a variable, then only change data value and (hopefully) the variable is used everywhere.
Of course, this value and the inevitable comparison to Deep Thought and The Hitchhiker's Guide to the Galaxy, is purely coincidental, I'm sure.
SA on 13 May 2021
Ohh, I got the solution from the following link https://www.mathworks.com/matlabcentral/answers/829123-extract-elements-of-each-cell-to-form-a-matrix-and-store-it-can-anyone-give-me-suggestions?s_tid=mlc_ans_email_view#comment_1518608. Thank you very much.