Filter löschen
Filter löschen

How to write a code for 3 Variables

3 Ansichten (letzte 30 Tage)
Gokhan Kayan
Gokhan Kayan am 25 Mär. 2018
Kommentiert: Gokhan Kayan am 27 Mär. 2018
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.

Akzeptierte Antwort

John D'Errico
John D'Errico am 25 Mär. 2018
Bearbeitet: John D'Errico am 25 Mär. 2018
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 Kommentar
Gokhan Kayan
Gokhan Kayan am 27 Mär. 2018
Thank you very much John this is what I exactly want :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Walter Roberson
Walter Roberson am 25 Mär. 2018
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 am 25 Mär. 2018
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.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by