Avoiding for loop for 1d-intepolation

Hi,
Generally, I try to avoid for loops. Is there any way of avoiding the following for loop?
for ii=1:length(alpha)
result(ii) = interp1(Eng_mat,res(:,ii),alpha(ii),'linear', 'extrap');
end
Dimension of the matrices: Eng_mat is 4000*1, res is 4000*10, alpha is 10*1
In principle, I need to use interpolation for each element of alpha according to ii'th coloumn of res.
I appreciate it if someone could help me with this.
Thanks

回答 (1 件)

Image Analyst
Image Analyst 2022 年 5 月 21 日

0 投票

I don't see a simpler way off the top of my head. You have only 10 iterations so I wouldn't worry about it. Ten iterations of a for loop will probably be faster than any other way you'd do it. If you had tens of millions of iterations then maybe it would be time to worry about a for loop, but for 10? Don't worry about it.

3 件のコメント

Omid Sharifi Sedeh
Omid Sharifi Sedeh 2022 年 5 月 21 日
編集済み: Omid Sharifi Sedeh 2022 年 5 月 21 日
Thanks for your kind reply. Well, of couse it can be 120 rather than 10 and as you say it might not affect the speed that much. But I have to call these lines at least 1 million times to get one of my data points.
Image Analyst
Image Analyst 2022 年 5 月 22 日
Over a million times? How do you get that from this:
"Dimension of the matrices: Eng_mat is 4000*1, res is 4000*10, alpha is 10*1"
Your loop is over alpha which has only 10 values.
Look, here is a loop that iterates a million times:
tic
for k = 1 : 1000
;
end
toc
Elapsed time is 0.000454 seconds.
So on my 10 year old computer a million iterations takes less than half a millisecond. So it's not the for loop itself that's taking up all the time. It's whatever you do inside of it.
Omid Sharifi Sedeh
Omid Sharifi Sedeh 2022 年 5 月 22 日
Well, I think there is a misunderstanding here. The actual code is way more complicated. What I meant is that this 'for' loop will be called 1 million times and not only one time over 10 iterations. The interpolation speed, on the other hand, depends on the dimensions of Eng_mat and res. If I increase it more, the runtime will be affected considerably.
Anyways, I used a trick and it seems to be working. I noticed that the desired results are stored in the first row of 'result':
result = interp1(Eng_mat,res,alpha,'linear', 'extrap');
result=result(1,:);
Thanks

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2019a

質問済み:

2022 年 5 月 21 日

コメント済み:

2022 年 5 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by