MATLAB Answers

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

조회 수: 16(최근 30일)
SA 2021년 5월 9일
댓글: SA 2021년 5월 13일
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 2021년 5월 9일
편집: dpb 2021년 5월 9일
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.
##### 댓글 수: 11표시숨기기 이전 댓글 수: 10
SA 2021년 5월 13일
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.

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!