Sum every i-th column in matrix seperately
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi all,
I have randomly generated matrix and I want to go through all columns and to sum every i-th column separately. I don't want to sum all the columns but to sum depending on the counter in for loop for example:
[a,b] = size(C);
for i = 1:b
S = sum(C(:,i))
S = 0 %but this doesn't work, result is sum of elements of all columns
0 Kommentare
Akzeptierte Antwort
Zikobrelli
am 12 Jun. 2014
Try sum(A(:,[1 4]))
where A is your random matrix.The line above will give you the sums of column 1 and 4.
ex: A=spiral(4)
sum(A(:,[1 4]))
ans = 34 46
8 Kommentare
Zikobrelli
am 12 Jun. 2014
You're using randi(generates random integer numbers) to build your matrix. then you add a last line (1:10) which means that you can NEVER have an all zeros column ,because the last line does not contain 0 Which means that the ONLY way to enter the if statement is to get an all ones column, which indeed does not happen often. The code works, you just need to run the program enough or choose a more suited matrix :)
Weitere Antworten (2)
Roger Stafford
am 12 Jun. 2014
S = sum(C(:,i:i:end),1);
This results in a row vector, S, consisting of the sum of every i-th column of C, as requested. It is not clear where you want the i-spaced columns to start. This starts at the i-th column. If you want them to start at the first column, change "i:i:end" to "1:i:end".
Jos (10584)
am 12 Jun. 2014
sumColsC = sum(C,1)
NotInteresting = sumColsC == 0 | sumColsC == size(C,2)
sumColsC(NotInteresting) = []
3 Kommentare
Zikobrelli
am 12 Jun. 2014
you're generating a random matrix.So yes, sometimes, you will not enter the if condition :)
try this
v=[]; C = [randi(2,4,10)-1]
[a,b] = size(C);
for i = 1:b
if (sum(C(:,i)) == 0) || (sum(C(:,i)) == a)
'I-th column is zero or ones , move on'
else v=[v sum(C(:,i))]
end
end
Jos (10584)
am 12 Jun. 2014
When you change the iterator in a for-loop, it will reset at the end
for k=1:10
disp(k) ;
k = 1 ;
disp(k) ;
end
You should be clearer about your goals. What do you mean with "move on"?
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!