Using if-else statement to determine which value to input into function
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Aayma Mughal
el 13 de Jun. de 2022
Comentada: Voss
el 13 de Jun. de 2022
Hello,
I am trying to calculate final grades from the data given in the screenshot. From left to right columns are
1) student ID
2) test 1 grade
3) test 2 grade
4) midterm grade
5) project grade
6) final grade
Tests are worth 10% and whichever test is higher is used in final calculation.
I am using the following to calculate final grades:
if samplegrades(:,2) > samplegrades(:,3)
t = samplegrades(:,2)
else
t = samplegrades(:,3)
end
m = samplegrades(:,4)
p = samplegrades(:,5)
f = samplegrades(:,6)
finalgrades = @(t,m,p,f) (t.*.10+m.*.20 + p.*.20+f.*.50)
finalgrades(t,m,p,f)
The problem is that the if-else statement doesn't seem to be using the higher t value. It is only using values from test2 to determine final grade. Please help if you can.
1 comentario
dpb
el 13 de Jun. de 2022
Read the doc for if, elseif, else carefully; particularly the part that explains how MATLAB determines what is TRUE.
Then see <find-array-elements-that-meet-a-condition> for introduction to logical addressing. It's possible to write the desired code w/o a for...end loop, but many beginners find that the easiest first.
Since this is a homework problem, we'll coach and let you figure out the next steps instead of just handing the solution to you...
Respuesta aceptada
Voss
el 13 de Jun. de 2022
t = max(samplegrades(:,2),samplegrades(:,3))
The if doesn't work as you expect because, when using an array condition in an if statement, the condition is considered true (so that the if-block executes) only when the condition is true for all elements of the array.
Example:
x = [1 2 3];
if x > 2 % not all elements of x are > 2
disp('true');
else
disp('false');
end
if x > 0 % all elements of x are > 0
disp('true');
else
disp('false');
end
For what you want to do in this case, you don't need an if, though. You can use max as shown above instead.
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!