Save variable to a matrix after a for loop
5 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
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!
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!