Help with Pre-allocating function values
3 次查看(过去 30 天)
显示 更早的评论
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
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
%% Vectorization method
[x,y] = meshgrid(lf, hf);
F = [x(:) y(:)].'
%Comparison
isequal(f, F)
采纳的回答
Stephen23
2023-11-12
The MATLAB approach:
lf = [697,770,852,941];
hf = [1209,1336,1477];
[X,Y] = meshgrid(lf,hf);
f = [X(:),Y(:)]
Or
T = combinations(lf,hf) % note output is a table!
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!