# My code is only returning the last output

3 visualizzazioni (ultimi 30 giorni)
Jackson il 4 Ott 2022
Risposto: Samuele Gould il 4 Ott 2022
Trying to un-vectorize matsum = sum(mat') and having difficulty. My code only returns the sum of the last column, any tips?
numrows = size(mat,1);
for i = 1:numrows
vec = mat(i,end);
for j = 1:length(vec)
end
disp(mat)
disp(vec)
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (2)

millercommamatt il 4 Ott 2022
vec = mat(i,end);
In this line you're always using the last column by specifying end. I think you want:
vec = mat(i,:);
If I'm reading your code correctly, I think what you're ultimately looking for is:
vec = sum(mat(:));
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Samuele Gould il 4 Ott 2022
I am not quite sure what you mean by un-vectorize, but if you want to find the sum of each column you can use the matlab function sum and specify the dimension (see the link).
The reason you are only getting the sum of the last column is because if mat is a n-by-m matrix, calling mat(i,end) will return the row i in the last column. To access all the columns you need mat(i,1:end).
numrows = size(mat,1);
for i = 1:numrows
vec = mat(i,end);
for j = 1:length(vec)
% returns the sum of all the elements of the matrix
end
disp(mat)
disp(vec)
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Logical in Help Center e File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by