matrix Question and row operations with a condition
3 views (last 30 days)
Show older comments
Hello
If i have a matrix N x M, for example a matrix S:
7 4 7
S = 4 2 4
0 2 -3
And i need to calculate for each row the average number. BUT there are some conditions!
1. If there is only one number, the final scalar = that number.
2. If there is more than 1 number, the average number is find by removing the lowest element in the vector and calculating the average number from the rest. The last condition: (HERE I AM HAVING TROUBLE)
3. IF ANY ELEMENT IN A ROW IS = -3 THEN THE FINAL SCALAR IS = -3. REGARDLESS OF THE OTHER 3 CONDITIONS.
My code in matlab is as follows (and it Works for the first to conditions):
[N M] = size(S);
i = 1:N;
% The logical vector to include the data:
logvec = true(size(S, 1), 1);
% The three ways to calculate the final scalar:
if M == 1
logvec = S(i,M);
elseif M > 1
logvec = (sum(S')-min(S'))/(M-1);
elseif M == -3 <--------Here is my problem!
logvec = -3; <--------Here is my problem!
end
% Display of the Final scalar:
gradesFinal = (logvec ');
end
Can someone please help me out with the last condition? It's obvious that the first to rows in the matrix S, gives: 7 and 4, but the last row should give -3. Because of the last "condition".
(Also i am a new user to matlab, only 10 days of programming :D Yaaay!! ) Thanks!
2 Comments
Accepted Answer
Stephen23
on 20 Jan 2015
Edited: Stephen23
on 20 Jan 2015
S = [7,4,7;4,2,4;0,2,-3;0,2,0];
Xn = S>0; % Or whatever your definition of "number" is.
X3 = any(S==-3,2);
X1 = ~X3 & sum(Xn,2)==1;
X2 = ~X3 & sum(Xn,2)>1;
M(X1,1) = S(bsxfun(@and,X1,Xn));
M(X2,1) = (sum(S(X2,:),2)-min(S(X2,:),[],2)) / (size(S,2)-1);
M(X3,1) = -3;
0 Comments
More Answers (1)
Ced
on 20 Jan 2015
Edited: Ced
on 20 Jan 2015
Your "M" is just the number of columns of your matrix, and does not containt any information about the values of the elements in your matrix. Since your matrix will never have a negative number of columns, that condition does not make much sense. To see if a row fulfils certain conditions, you may want to have a look at the "any" function, e.g.
a = [ 1 2 3 ];
check_if_2 = any(a==2); % true
check_if_5 = any(a==5); % false
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!