Iterating through 2 Arrays and Performing a Calculation

A1 = [5 10 15 20 25 30 35 40]
A2 = [ 7 22 38]
Goal: Iterate through A2 and subtract from appropriate value in A1, store this value in a separate array.
Example:
7 in A2 is between 10 and 5 where
t1= 5
t2 = 10
Subtract A2 from t1.
7-5 = 2 (store this value in a separte array.
Move on to the second element in A2, 22. 22 is between 20 and 25. Substract (22-20) = 2; store this value

4 件のコメント

Sindar
Sindar 2020 年 3 月 6 日
Is A1 always evenly spaced? Is it always sorted? Will A2 ever have elements greater than all elements in A1?
Graduate Student
Graduate Student 2020 年 3 月 6 日
A2 is not evenly space but it sorted. The next value is always bigger than the previous.
I'm not sure what you mean by third question. A2 will aways be larger than T1. So when you subtract, it will always be a positive integer.
Sindar
Sindar 2020 年 3 月 6 日
編集済み: Sindar 2020 年 3 月 6 日
Ah, sorry, I asked the wrong question: Will A2 ever have elements less than all the elements in A1? (so t1 doesn't exist). Also, how many elements, roughly, will A1 and A2 have?
Graduate Student
Graduate Student 2020 年 3 月 6 日
There are about ~1000 elements in each array although each array is a different length from each other. No, A2 will not be less than A1. Thanks!

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

回答 (1 件)

Sindar
Sindar 2020 年 3 月 6 日

0 投票

loop version:
for ind=1:length(A2)
idx = find(A1 < A2(ind),1,'last');
A3(ind) = A2(ind) - A1(idx);
end
Another (probably much worse) way of looking at it for smallish arrays:
A1 = [3 10 15 20 25 30 35 40];
A2 = [ 7 22 38];
% create a matrix of all combinations of A1(i)-A2(j)
tmp = A2-A1';
% set any less than zero to infinity
tmp(tmp<0)=Inf;
% find the minimum for each column
A3 = min(tmp)

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

質問済み:

2020 年 3 月 6 日

回答済み:

2020 年 3 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by