Calculating the sum of each row in a matrix.

Hi,
I have a code like this:
X = [1 2 3 4 5;
3 5 7 9 11;
2 4 6 8 10;
3 9 12 15 18];
minx = min(X, [ ], 2); %min of each vector
maxx = max(X, [ ], 2); %max of each vector
result = X >= reshape(minx, 1, 1, [ ]) & X <= reshape(maxx, 1, 1, [])
When i run it,
result is 4x5x4 logical and
val(:,:,1) =
1 1 1 1 1
1 1 0 0 0
1 1 0 0 0
1 0 0 0 0
Here i have a question.
I would like to see the sum of each row with names.
In val(:,:,1), the sum of first row= A11, sum of second row= A12, sum of third row= A13 and sum of fourth row=A14 .
Likewise for
val(:,:,2) =
0 0 1 1 1
1 1 1 1 1
0 1 1 1 1
1 1 0 0 0
sum of first row= A21, sum of second row= A22,...
I tried to do this with creating a 4X4 matrix A which consist of the sum values A11, A12, A13 A14, .... But i cant do it.
Any help is appreciated.

3 comentarios

Stephen23
Stephen23 el 7 de Feb. de 2020
Editada: Stephen23 el 7 de Feb. de 2020
"I would like to see the sum of each row with names."
Putting numbers into variable names is a sign that you are doing something wrong.
Putting meta-data into variable names is a sign that you are doing something wrong.
Accessing variable names dynamically is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
You can trivially access the elements of an array using indexing. Indexing is neat, simple, easy to debug, and very efficient (unlike what you are trying to do). You should use indexing.
PS: Your code does not define val, so we have no idea how it relates to your example code or the requested output.
Guillaume
Guillaume el 7 de Feb. de 2020
Note that this is a follow-up to this question
Adam Danz
Adam Danz el 8 de Feb. de 2020
Note #2: this quesiton may have migrated to a new question.

Iniciar sesión para comentar.

Respuestas (1)

Sourav Bairagya
Sourav Bairagya el 12 de Feb. de 2020
You can use 'sum' function to compute sum for each row and then can apply 'squueze' function to remove the singleton dimension (i.e. dimension with length 1). After that you can take transpose of the result and you will get the desired output.
val = sum(result,2);
out = squeeze(val);
A = out';
You can leverage these links for further information:

1 comentario

Guillaume
Guillaume el 12 de Feb. de 2020
Editada: Guillaume el 12 de Feb. de 2020
Or you can do the squeeze and transpose altogether with just one permute:
A = permute(sum(result, 2) [2 3 1]) %note this do a .' transpose instead of a ' ctranspose. For a logical array the two are the same.

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 7 de Feb. de 2020

Editada:

el 12 de Feb. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by