Save variable to a matrix after a for loop

조회 수: 3 (최근 30일)
Miguel Albuquerque
Miguel Albuquerque 2022년 6월 11일
댓글: Miguel Albuquerque 2022년 6월 12일
Hey guys this is probably very easy, but Im having troubles doing it.
I have this code, that cross-correlates two signals, from 2 matrixes. I would like to save all the outputs of the function in 3 matrixes(afmag3,delay3,doppler3). Also the code, takes too long to run , I dont know if this can be better. Thank you
[n,m]=size(surv_matrix);
[n2,m2]=size(ref_matrix);
for i=1:m
for ii=1:m2
Reference_SignalCut=ref_matrix(:,ii);
Surveillance_SignalCut=surv_matrix(:,i);
[afmag3,delay3,doppler3] = ambgfun(Reference_SignalCut,Surveillance_SignalCut,fs,[1e6 1e6]);
afmag3 = afmag3*1; % Select plot gain *1
afmag3(afmag3>1 )= 1;
end
end

채택된 답변

Jan
Jan 2022년 6월 11일
편집: Jan 2022년 6월 11일
[n, m] = size(surv_matrix);
[n2, m2] = size(ref_matrix);
afmag3 = cell(m, m2);
delay3 = cell(m, m2);
doppler3 = cell(m, m2);
for i=1:m
S = surv_matrix(:,i); % Surveillance of cut signal
for ii=1:m2
R = ref_matrix(:,ii); % Reference of cut signal
[tmp, delay3{i, ii}, doppler3{i, ii}] = ambgfun(R, S, fs, [1e6 1e6]);
afmag3{i, ii} = max(1, tmp);
end
end
Concerning the run time, use the profile 'r to finde the bottleneck. If ambgfun could be vectoprized maybe a speedup is possible.
I've moved the definition of Surveillance_SignalCut out of the inner loop. This does not save a lot of time, but it is a good programming practice not to do any work repeatedly. afmag3 = afmag3*1 was a waste of time only.
Avoid complicated names for variables, because this impedes the reading. Explain the meaning of a variable in a comment instead.
  댓글 수: 5
Jan
Jan 2022년 6월 11일
[time_SS,Surveillance_Signal]=deal(nan(n,m));
% Looks more complicated and takes longer than:
time_SS = nan(n, m);
Surveillance_Signal = nan(n, m);
I'd omit the "_Signal". Could it be anything else than a signal? Short names reduce the clutter.
Why do you use NaNs to pre-allocate the array? All values are overwritten, so zeros are cheaper: zeros(1e6, 1) is 50 times faster than NaN(1e6, 1);
What is freq2time()? Could it be vectorized? If so, you could omit the loops. But the loops do not anything at all, because the loop index i does not occur inside the loop anywhere.
If yourt code produces the correct output, simplify:
[time_SS,Surveillance_Signal]=deal(nan(n,m));
for i=1:m
[time_SS,Surveillance_Signal]=freq2time(m,doppler_freqSurv);
end
to
[time_SS,Surveillance_Signal]=freq2time(m,doppler_freqSurv);
% No loop, no pre-allocation!
Miguel Albuquerque
Miguel Albuquerque 2022년 6월 12일
Thanks a lot for the help :D

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by