matrix Question and row operations with a condition

3 visualizzazioni (ultimi 30 giorni)
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 Commenti
Stephen23
Stephen23 il 20 Gen 2015
Modificato: Stephen23 il 20 Gen 2015
What do you mean by "number"? 0 is a number, as is -3.14159, and also 2+3i. What about just i ? Do you mean to only exclude Inf and NaN values from being "numbers" ?
Remember that the integers also include zero and the negative integers.
Image Analyst
Image Analyst il 20 Gen 2015
Sounds very much like your homework - is it?

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 20 Gen 2015
Modificato: Stephen23 il 20 Gen 2015
You could avoid the for loop and use the power of MATLAB's indexing :
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;

Più risposte (1)

Ced
Ced il 20 Gen 2015
Modificato: Ced il 20 Gen 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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by