필터 지우기
필터 지우기

How to write a code for 3 Variables

조회 수: 3 (최근 30일)
Gokhan Kayan
Gokhan Kayan 2018년 3월 25일
댓글: Gokhan Kayan 2018년 3월 27일
I want to write a code to obtain a new value array that is dependent to 3 variables. My 3 variables are like the table shown below:
A B C
1 400 200
1 500 100
2 455 300
2 200 400
3 100 500
3 500 600
2 600 100
3 700 900
1 800 150
2 900 150
I want to calculate new 'D' array from A,B,C. My code should be like this if A=1 then calculate the sum of B and divide it to sum of C.
For example we have 3 row that A=1 and we have B=400,500,900 C=200,100,150 for A=1. So it shoulde be 400 +500+900 /200+100+150. The result (D) is 4 for A=1. I have so many A values and ı don't know how to calculate all of them. If you help me, I will be very happy. Thank you.

채택된 답변

John D'Errico
John D'Errico 2018년 3월 25일
편집: John D'Errico 2018년 3월 25일
Easy peasy. What, 2 lines?
abc = [1 400 200
1 500 100
2 455 300
2 200 400
3 100 500
3 500 600
2 600 100
3 700 900
1 800 150
2 900 150];
[ai,bcsum] = consolidator(abc(:,1),abc(:,2:3),@sum)
ai =
1
2
3
bcsum =
1700 450
2155 950
1300 2000
bcratio = bcsum(:,1)./bcsum(:,2)
bcratio =
3.7778
2.2684
0.65
There is no need for the A values to be integers. As long as they are distinct will suffice.
  댓글 수: 1
Gokhan Kayan
Gokhan Kayan 2018년 3월 27일
Thank you very much John this is what I exactly want :)

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

추가 답변 (2개)

Walter Roberson
Walter Roberson 2018년 3월 25일
sumB = accumarray(A, B);
sumC = accumarray(A, C);
D = sumB ./ sumC;
D(sumB == 0 & sumC == 0) = 0;
This applies directly only if the A values are positive integers, preferably small and consecutive. If they are not positive integers then there is an adjustment that can be made using unique()
The final setting to 0 is for the case where the sum of B and sum of C are both 0, replacing the NaN that would result with 0. The sums could be 0 if the entries can be positive and negative; the sums can also be 0 if there is a gap in the values of A, such as if A might be [1, 2, 4] with no 3 entry.

Geoff Hayes
Geoff Hayes 2018년 3월 25일
Gokhan - you can do
A==1
to return an array of logical values, zeros and ones, that will tell you which element of A is a one (indicated by a one) and which element of A is not a one (indicated by a zero). For example,
A = [1 2 3 4 5 1 1]
then
A==1
returns
1 0 0 0 0 1 1
And so you could then do
sum(B(A==1))
to sum those elements of B that correspond to ones within A. See logical indexing for more details.
  댓글 수: 1
Gokhan Kayan
Gokhan Kayan 2018년 3월 27일
Thanks for your respond Geoff :)

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

카테고리

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