Adding elements of arrays conditionally

1 view (last 30 days)
KV
KV on 20 Mar 2013
Hi I have arrays x1, y1 of 10 elements each and arrays x2, y2 with 15 elements each. I also have array z1 which is 10 x 10 array, and z2 which is 15 x 15 (z1 elements corresponding to each combination of x1 and y1 indexes, and z2 corresponding to each combination of x2 and y2 indexes)
All the elements of x1 can be found in x2 (other 5 elements are randomly scattered between values which correspond to x1) Same goes for y1 and y2 as well.
For example:
x1 = [100,200,300,400,.....1000]
x2 = [100,150,200,300,400,450...1000,1100]
What I am trying to do is: depending on the value of x1 and y1, add the corresponding value of z1 to that of z2 (when a value of x1(n)=x2(m), and y1(a)=y2(b)). So basically if x1(n) == x2(m) && y1(a)==y2(b), then z3 = z1(n,a) + z2 (m,b)
I want to have an array built of z3 values (10x10).
I hope this question makes sense.
Are there any efficient and easy ways to implement this sort of approach in Matlab?
Many thanks
  2 Comments
KV
KV on 20 Mar 2013
What part is not clear? I have reworded some of it if it helps.

Sign in to comment.

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 20 Mar 2013
Edited: Azzi Abdelmalek on 20 Mar 2013
EDIR
[xx1 yy1]=meshgrid(x1,y1);
[xx2 yy2]=meshgrid(x2,y2);
for k=1:10
for p=1:10
idx=find(xx2==xx1(k,p),1);
idy=find(yy2==yy1(k,p),1);
z3(k,p)=z1(idx)+z2(idy);
end
end

Azzi Abdelmalek
Azzi Abdelmalek on 20 Mar 2013
Try this
[xx1 yy1]=meshgrid(x1,y1);
[xx2 yy2]=meshgrid(x2,y2);
for k=1:10
for p=1:10
[n,~]=find(xx2==xx1(k,p),1)
[~,b]=find(yy2==yy1(k,p),1)
z3(k,p)=z1(k,p)+z2(n,b)
end
end
  1 Comment
KV
KV on 20 Mar 2013
Edited: KV on 20 Mar 2013
Many thanks for the Answer Azzi. The approach is a great pointer in the right direction. The exact code unfortunately doesn't give the right values besides the very first element.

Sign in to comment.

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!