matrix Question and row operations with a condition
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2015-1-20
编辑:Stephen23
2015-1-20
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 个评论
更多回答(1 个)
Ced
2015-1-20
编辑:Ced
2015-1-20
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!