I want to add some elements of a vector depending on the elements of other vector
1 次查看(过去 30 天)
显示 更早的评论
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! :)
0 个评论
采纳的回答
Azzi Abdelmalek
2016-4-17
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 个评论
Azzi Abdelmalek
2016-4-17
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
更多回答(1 个)
Andrei Bobrov
2016-4-17
编辑:Andrei Bobrov
2016-4-17
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!