Help with Pre-allocating function values

조회 수: 5 (최근 30일)
Mason
Mason 2023년 11월 12일
이동: Dyuman Joshi 2023년 11월 12일
Does anyone know how I might be able to go about preallocating f = []; I keep getting hit with the same "arrays dont match" error, I also noticed that if f isnt cleared it tends to add an extra column to the array. Ive noticed this particular portion of my function is extremely slow and it would help alot with the dial im making;
lf = [697 770 852 941]; % Low frequency group
hf = [1209 1336 1477]; % High frequency group
f = [];
for c = 1:4
for r = 1:3
f = [f [lf(c); hf(r)]];
end
end
Thanks,
  댓글 수: 2
Dyuman Joshi
Dyuman Joshi 2023년 11월 12일
이동: Dyuman Joshi 2023년 11월 12일
Dynamically growing arrays is detrimental to the performance of the code. You should Preallocate arrays according to the final output size.
However, you can vectorize this operation -
lf = [697 770 852 941]; % Low frequency group
hf = [1209 1336 1477]; % High frequency group
%% Original method
f = [];
for c = 1:4
for r = 1:3
f = [f [lf(c); hf(r)]];
end
end
f
f = 2×12
697 697 697 770 770 770 852 852 852 941 941 941 1209 1336 1477 1209 1336 1477 1209 1336 1477 1209 1336 1477
%% Vectorization method
[x,y] = meshgrid(lf, hf);
F = [x(:) y(:)].'
F = 2×12
697 697 697 770 770 770 852 852 852 941 941 941 1209 1336 1477 1209 1336 1477 1209 1336 1477 1209 1336 1477
%Comparison
isequal(f, F)
ans = logical
1
Mason
Mason 2023년 11월 12일
이동: Dyuman Joshi 2023년 11월 12일
Stephen responded a little faster but, thank you for the additional information helps in the long run

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

채택된 답변

Stephen23
Stephen23 2023년 11월 12일
The MATLAB approach:
lf = [697,770,852,941];
hf = [1209,1336,1477];
[X,Y] = meshgrid(lf,hf);
f = [X(:),Y(:)]
f = 12×2
697 1209 697 1336 697 1477 770 1209 770 1336 770 1477 852 1209 852 1336 852 1477 941 1209
Or
T = combinations(lf,hf) % note output is a table!
T = 12×2 table
lf hf ___ ____ 697 1209 697 1336 697 1477 770 1209 770 1336 770 1477 852 1209 852 1336 852 1477 941 1209 941 1336 941 1477

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by