Writing a simple loop
Mostrar comentarios más antiguos
Given: For this exercise, you will write code to sum all the positive integers in a matrix of random integers and save that sum in variable S. Additionally, your code should save the sum of all negative integers in variable N.
Find : I need to write code that includes a pair of nested loops that cycles through each element in matrix A and checks to see if it is positive. If the value in the current element is positive, add that value to your current sum S. If it is not, add that value to your current sum N.
The script below has already been pre-populated with a line of code to generate a matrix A for you. Please don't change the value of A in your code.
Hints:
A is a 7x10 matrix, but if you didn't know that you can always have Matlab go figure out the size for you.
Make sure you are checking each and every element. Every column in every row or every row in every column.
Once you have gotten your code to evaluate correctly using loops, try thinking of another way you could come up with the solution without using loops. Consider using logicals rather than loops... When you do this successfully, the first 2 pretests will evaluate as correct and the 3rd will evaluate as incorrect. Submit this solution as well even though, it says the solution is incorrect.
Issue: I think I am using loops incorrectly, I defaulted to using logicals because that's what makes the most sense to me, but I would like to know how the loop SHOULD work.
My Solution:
A=randi([-50 50],7,10);
size(A)
for A>=0
S=sum(A)
if A<=0
N=sum(A)
end
end
4 comentarios
Stephen23
el 19 de Mzo. de 2024
"Issue: I think I am using loops incorrectly,"
The FOR documentation shows this syntax at the top of the page:
for index = values
statements
end
Does your code follow the syntax given in the documentation? Take a look at the examples.
Dyuman Joshi
el 19 de Mzo. de 2024
I, once again, suggest you to take the free MATLAB Onramp tutorial to learn the syntaxes and fundamentals of MATLAB.
Also, refer to the official documentation for acceptable syntaxes for a function.
P.S - This is not a nested loop, just a simple for loop.
DGM
el 19 de Mzo. de 2024
Three hints in no particular order:
% configure your loops based on the subscript ranges needed
for row = 1:size(A,1)
for col = 1:size(A,2)
% ...
end
end
and
% initialize or preallocate outputs as needed
S = 0;
N = 0;
and
% update accumulated sums as needed
S = S + A(row,col);
Spaceman
el 21 de Mzo. de 2024
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!