Writing a simple loop

4 views (last 30 days)
Spaceman
Spaceman on 19 Mar 2024
Commented: Spaceman on 22 Mar 2024
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 Comments
DGM
DGM on 19 Mar 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
Spaceman on 21 Mar 2024
I understand. I want to talk to MATLAB in a different way than it likes. As Mr. Joshi has mentioned I will try to complete ONRAMP with hopes I can learn the language a bit better and not get so lost in translation.

Sign in to comment.

Accepted Answer

Shubham
Shubham on 22 Mar 2024
Hi Kyle,
It looks like you're attempting to use a for loop in MATLAB in a way that's not syntactically correct for iterating through each element of the matrix A. To properly sum positive and negative integers in a matrix using loops, you need to explicitly iterate over each element of the matrix and check if it's positive or negative, then add it to S or N accordingly. Here's how you can do it using nested loops:
% Given matrix A
A = randi([-50, 50], 7, 10);
% Initialize sum variables
S = 0; % Sum of positive integers
N = 0; % Sum of negative integers
% Get the size of the matrix A
[rows, cols] = size(A);
% Iterate through each element of A
for i = 1:rows
for j = 1:cols
if A(i,j) > 0
% If the element is positive, add it to S
S = S + A(i,j);
else
% If the element is negative or zero, add it to N
N = N + A(i,j);
end
end
end
% Display the results
disp(['Sum of Positive Integers: ', num2str(S)]);
disp(['Sum of Negative Integers: ', num2str(N)]);
This code correctly uses nested for loops to iterate over each element in the matrix A, checking if each element is positive or negative, and then adds it to the appropriate sum.
Using Logical Indexing (Alternative Method)
For the alternative method without loops, you can use logical indexing to find positive and negative elements and sum them directly. However, remember that this method is expected to fail the 3rd pretest based on your instructions.
% Given matrix A
A = randi([-50, 50], 7, 10);
% Sum of positive integers
S = sum(A(A > 0));
% Sum of negative integers
N = sum(A(A < 0));
% Display the results
disp(['Sum of Positive Integers: ', num2str(S)]);
disp(['Sum of Negative Integers: ', num2str(N)]);
This method leverages MATLAB's ability to perform operations on arrays using logical conditions directly, which is more efficient but doesn't use explicit loops as your task requires for the first part of the solution.
  1 Comment
Spaceman
Spaceman on 22 Mar 2024
Eureka! I will inevitable learn how to syntax properly. I just think "I" need to go through so many iterations to get closer and closer to the correct form. Thank you for laying this out for me to gorge on. I am digesting every line of code and am very satisfied. It all makes sense when I see it, but in my minds eye I find trouble in initializing that which needs to be entered to attain these results.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!