matrix addition according to position vector

2 visualizaciones (últimos 30 días)
Rabb
Rabb el 6 de Feb. de 2023
Respondida: Voss el 6 de Feb. de 2023
Hello, i have matrix A wich is 2xn dimension and vector b that is 1xn. I want to sort and sum A acording to vector b. for explamle
A=[1 3 5 7 9 11;
2 4 6 8 10 12]
b=[1 1 3 4 5 3]
so answer would be
C=[4 0 16 7 9
6 0 18 8 10]

Respuesta aceptada

Voss
Voss el 6 de Feb. de 2023
A=[1 3 5 7 9 11;
2 4 6 8 10 12];
b=[1 1 3 4 5 3];
Maybe something like this:
C = zeros(size(A));
ub = unique(b);
for ii = 1:numel(ub)
C(:,ub(ii)) = sum(A(:,b == ub(ii)),2);
end
disp(C);
4 0 16 7 9 0 6 0 18 8 10 0
Another way:
[bg,gidx] = findgroups(b);
C = zeros(size(A));
C(:,gidx) = splitapply(@(x)sum(x,2),A,bg);
disp(C);
4 0 16 7 9 0 6 0 18 8 10 0

Más respuestas (1)

Vilém Frynta
Vilém Frynta el 6 de Feb. de 2023
This looks like homework.
It seems like you know what kind of functions you should work with. I'd recommend to study the documention of these functions and try to think it out. Feel free to share your progress.
If you are beginning with Matlab, it's good idea just to try (and learn from mistakes and experiments).

Categorías

Más información sobre Fourier Analysis and Filtering 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