Setting X as a column of a matrix

So I have another question: How do i tell MATLAB to go thru the matrix and take the second column of this and apply it to the if statement i have coded below:
M = [1, 80.8 %A Matrix for the grades
2, 79
3, 87.4
4, 74.2
5, 82
6, 85]
%The following if, else if and else statement calculates the grades based
%on the values of X.
if X<60
y = F
elseif X>=60 & X<70
y = D
elseif X>=70 & X<80
y = C
elseif X>=80 & X<90
y = B
else
y = A
end
After I do that, I want it to output into a matrix like the one above, but with another column where the y will go.

 Réponse acceptée

Matt Fig
Matt Fig le 11 Sep 2012
Modifié(e) : Matt Fig le 11 Sep 2012

0 votes

Use a FOR loop to loop over the rows of column 2. But you are going to want to define A,B,C,D,F or you will get errors. Unless you mean 'A','B','C','D','F'. And to store the values, assign each one to a position in an array.
for ii = 1:length(M)
X = M(ii,2); % Assign this value to X, each time through
if X<60
y = F;
elseif X>=60 & X<70
y = D;
elseif X>=70 & X<80
y = C;
elseif X>=80 & X<90
y = B;
else
y = A;
end
GR(ii) = y
end

3 commentaires

Jonathon
Jonathon le 13 Sep 2012
Well what I am looking for, to be more specific, is for it to take the values of column 2, assign a letter grade, and be able to print the resulting values into a new matrix.
Matt Fig
Matt Fig le 13 Sep 2012
Modifié(e) : Matt Fig le 13 Sep 2012
So did you try it? Like I said, you should use 'A' instead of A, 'B' instead of B...
M = [1, 80.8 %A Matrix for the grades
2, 79
3, 87.4
4, 74.2
5, 82
6, 85]
for ii = 1:length(M)
X = M(ii,2);
if X<60
y = 'F';
elseif X>=60 & X<70
y = 'D';
elseif X>=70 & X<80
y = 'C';
elseif X>=80 & X<90
y = 'B';
else
y = 'A';
end
GR(ii) = y;
end
GR.'
Jonathon
Jonathon le 13 Sep 2012
Yeah I have, thanks I've gathered all I need.

Connectez-vous pour commenter.

Plus de réponses (2)

Matt Kindig
Matt Kindig le 11 Sep 2012

0 votes

You can also do this using logical indexing, which is a more "Matlab-y" way to do this problem...
y = repmat('A', size(M(:,1))); %set default grade to 'A'
X = M(:,2);
%these various truth conditions assign letter grade appropriately
y(X<60) = 'F';
y(X>=60 & X<70) = 'D';
y(X>=70 & X<80) = 'C';
y(X>=80 & X<90)= 'B';

1 commentaire

Matt Fig
Matt Fig le 12 Sep 2012
See the OP's previous post for more info...

Connectez-vous pour commenter.

Andrei Bobrov
Andrei Bobrov le 12 Sep 2012
Modifié(e) : Andrei Bobrov le 13 Sep 2012

0 votes

M = [1, 80.8 %A Matrix for the grades
2, 79
3, 87.4
4, 74.2
5, 82
6, 85];
x = cellstr(['F';('D':-1:'A')']); % OR x = ['F';('D':-1:'A')'];
[a,b] = histc(M(:,2),[-inf,(6:9)*10,inf]);
out = x(b);
OR
x = ['F';('D':-1:'A')'];
out = x(sum(bsxfun(@gt,M(:,2),[-inf,(6:9)*10,inf]),2));

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by