I want to sum up specific array in a matrix

1 visualización (últimos 30 días)
Bhagya Lakshmi Marella
Bhagya Lakshmi Marella el 22 de Jun. de 2019
Comentada: KALYAN ACHARJYA el 24 de Jun. de 2019
For example If I have a matrix like this
x = [ 2.356 37
1.351 39
4.394 37
3.622 39
4.489 39
3.135 37
6.653 39 ]
I want to sum up the values that are specific to 37 and 39 seperatly only if it is alternative. If 39 and 37 are not alternative like in 4th and 5 th row wants to add that to the next subsecuent value in this case it is 37.
Some of the 37 should be (2.356+4.394+4.489+3.135), 39 should be (1.351+3.622+6.653). Please help in getting a matlab code for this!
Thank you in advance
  3 comentarios
Bhagya Lakshmi Marella
Bhagya Lakshmi Marella el 22 de Jun. de 2019
sum_37 should be =2.356+4.394+4.489+3.135
sum_39 should be =1.351+3.622+3.5147+3.6058+2.827+3.6134+6.653
Bhagya Lakshmi Marella
Bhagya Lakshmi Marella el 24 de Jun. de 2019
sum_37 should be =2.356+4.394+4.489+3.135
sum_39 should be =1.351+3.622+3.5147+3.6058+2.827+3.6134+6.653
Please help me to get this!

Iniciar sesión para comentar.

Respuesta aceptada

Shwetank Shrey
Shwetank Shrey el 24 de Jun. de 2019
Hope this helps you.
function [sum_37, sum_39] = compute_sum(x)
sum_37 = 0;
sum_39 = 0;
found_37 = false;
found_39 = false;
for i = 1 : length(x)
if x(i, 2) == 37
if ~found_37
sum_37 = sum_37 + x(i, 1);
found_37 = true;
found_39 = false;
else
sum_39 = sum_39 + x(i, 1);
end
else
if ~found_39
sum_39 = sum_39 + x(i, 1);
found_39 = true;
found_37 = false;
else
sum_37 = sum_37 + x(i, 1);
end
end
end
end

Más respuestas (1)

KALYAN ACHARJYA
KALYAN ACHARJYA el 22 de Jun. de 2019
Editada: KALYAN ACHARJYA el 22 de Jun. de 2019
x =[2.356 37
1.351 39
4.394 37
3.622 39
4.489 39
3.135 37
6.653 39]
idx=(find(x(:,2)==37))';
sum_37=0;
for i=1:length(idx)
sum_37=sum_37+x(idx(i),1);
end
% You can do the same for 39 too
Wait I am providing the same without loop
idx=(find(x(:,2)==37))';
sum_37=sum(x(idx(:),1));
For 39:
idx=(find(x(:,2)==39))';
sum_39=sum(x(idx(:),1));
  2 comentarios
Bhagya Lakshmi Marella
Bhagya Lakshmi Marella el 22 de Jun. de 2019
Thank you so much!
This works to add up the elements that are specific to a 37 and 39. But, If 39 and 37 are not alternative like in 4th and 5 th row, I want to add that to the next subsecuent value in this case 4.489 should be added to 37.
KALYAN ACHARJYA
KALYAN ACHARJYA el 24 de Jun. de 2019
You can do that using 1/2 line of logical statments and index comparision.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by