Sum of each row ?

2 Ansichten (letzte 30 Tage)
Trevor Badji
Trevor Badji am 10 Dez. 2017
Kommentiert: Image Analyst am 26 Dez. 2017
I have [1 1 0; 0 1 0; 0 0 0;] and I want to write that if average of each row > 0.5 it equals 1 , else 0
for the example above, first row 1+1+0 / 3 > 0.5 then it is 1 ..
for i=1:length(nx);
s(i)= sum(nx(i,:))/3;
for n=1:length(nx);
if s(i(n+1))> 0.5;
s(i(n+1)) == 1;
else
s(i(n+1))== 0 ;
end
end
end
  2 Kommentare
Star Strider
Star Strider am 10 Dez. 2017
What functions are you permitted to use in this obvious homework assignment?
Rena Berman
Rena Berman am 26 Dez. 2017
(Answers Dev) Restored edit

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Jos (10584)
Jos (10584) am 10 Dez. 2017
Use the matlab way! Use the functions mean, or sum and size. Read the documentation on these functions and pay attention to the dimension argument.
Then take a closer look at logical operators, like >
A = [.9 .7 .4 .6 .2]
B = A > 0.5

Image Analyst
Image Analyst am 10 Dez. 2017
Bearbeitet: Image Analyst am 10 Dez. 2017
Does it have to be a for loop? Why not just do:
rowMeans = mean(nx, 2);
s = zeros(size(nx));
s(rowMeans > 0.5, :) = 1;
You've said both "sum" and "average" - which is it?????. The above is for average. If you want sums, do
rowSums = sum(nx, 2);
s = zeros(size(nx));
s(rowSums > 0.5, :) = 1;
  3 Kommentare
Stephen23
Stephen23 am 11 Dez. 2017
"There are no specific number of rows therefore i am trying to use for loop to see average of each row"
This makes no sense: vectorized code has no restrictions on how many rows it can handle. Why do you think that a loop is required?
Image Analyst
Image Analyst am 26 Dez. 2017
Original question:
I have [1 1 0; 0 1 0; 0 0 0;] and I want to write that if average of each row > 0.5 it equals 1 , else 0
for the example above, first row 1+1+0 / 3 > 0.5 then it is 1 ..
for i=1:length(nx);
s(i)= sum(nx(i,:))/3;
for n=1:length(nx);
if s(i(n+1))> 0.5;
s(i(n+1)) == 1;
else
s(i(n+1))== 0 ;
end
end
end

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 10 Dez. 2017
mean(nx, 2) > 0.5 %the 2 means "by rows" here.

Kategorien

Mehr zu Startup and Shutdown 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!

Translated by