Adding elements of arrays conditionally

조회 수: 9 (최근 30일)
KV
KV 2013년 3월 20일
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
Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 20일
This is not clear
KV
KV 2013년 3월 20일
What part is not clear? I have reworded some of it if it helps.

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

답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 20일
편집: Azzi Abdelmalek 2013년 3월 20일
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 2013년 3월 20일
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
KV
KV 2013년 3월 20일
편집: KV 2013년 3월 20일
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.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by