I want to add some elements of a vector depending on the elements of other vector

1 visualizzazione (ultimi 30 giorni)
Hello everyone! I am new using Matlab so for me would be really useful if you help me to answer this question.
I have two vectors of the same size: t=[1; 1; 1; 2; 2; 3; 3; 3; 3]; x=[10; 11; 12; 21; 24; 30; 30; 40; 30]; and I want to add elements in X wich correspond to the same number in t, the result should look like this Z=[0;0;33;0;45;0;0;0;130] any help is welcome, thanks a lot! :)

Risposta accettata

Azzi Abdelmalek
Azzi Abdelmalek il 17 Apr 2016
t=[1; 1; 1; 2; 2; 3; 3; 3; 3]
x=[10; 11; 12; 21; 24; 30; 30; 40; 30]
v=accumarray(t,x)
[~,jj]=unique(t,'last')
out=zeros(size(t))
out(jj)=v
  3 Commenti
Azzi Abdelmalek
Azzi Abdelmalek il 17 Apr 2016
Ok, we have to make some changes to the code
t=[726835; 726835; 726835; 726836; 726836; 726837; 726837; 726837; 726837];
x=[1.80232785962791e-07;4.24203429768918e-07;2.00633247309213e-08;2.05570729341328e-07;3.93731790512878e-08;1.62955844917509e-06;9.75259887592940e-08;8.06274553635844e-10;6.53267877563658e-08];
[~,jj,ii]=unique(t,'last')
v=accumarray(ii,x)
out=zeros(size(t))
out(jj)=v

Accedi per commentare.

Più risposte (1)

Andrei Bobrov
Andrei Bobrov il 17 Apr 2016
Modificato: Andrei Bobrov il 17 Apr 2016
t=[726835; 726835; 726835; 726836; 726836; 726837; 726837; 726837; 726837];
x=[1.80232785962791e-07;4.24203429768918e-07;2.00633247309213e-08;...
2.05570729341328e-07;3.93731790512878e-08;1.62955844917509e-06;...
9.75259887592940e-08;8.06274553635844e-10;6.53267877563658e-08];
[~,~,n] = unique(t);
k = find(diff([n;n(end)+1]));
Z = accumarray(k(n),x);

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by