How do i use a pair of nested for loops to store a series of 9 related numbers in a 3x3 matrix?
2 views (last 30 days)
Show older comments
Use a pair of nested for loops to store a series of 9 related numbers in a 3 x 3 matrix (the outer loop determines which row and the inner loop determines which column to store each value in the series). Your code should prompt the user for the starting value and the increment of the series. For example, if the user inputs a starting value of 7 and increment of 2 then the matrix should look like the following 7 9 11 ;13 15 17 ;19 21 23
part of the code was given to us at the part that says "=input "not sure what goes in there
and when i run i get error : Undefined function or variable 'startvalue'.
A= input ('Enter a real number for the starting value of your series. ');
= input % complete this command
value = startvalue;
X= zeros(3,3); % initialize the 3x3 matrix
a =1;
b=1;
for rows = 1:3
for colm =1:3
X(rows,colm)= a +(rows*colm-1)*b
end
end
0 Comments
Accepted Answer
Stephen23
on 27 Jan 2019
A = str2double(input('start:','s'));
S = str2double(input('step:','s'));
X = nan(3,3);
for R = 1:3
for C = 1:3
X(R,C) = A;
A = A+S;
end
end
2 Comments
Stephen23
on 27 Jan 2019
Edited: Stephen23
on 28 Jan 2019
The first three lines that you were given seem to be
- badly written
- buggy
which is why my first three lines look different. In particular:
- input is useful (if overused by beginners and professors), but has the risk that it evaulates anything that the user enters, even code or commands. By wrapping it in a str2double call and making it return only a character vector (using the 's' option) then it is guaranteed that the output is always numeric.
- startvalue is not defined, and I see no point in duplicating the same data into multiple variables. Thus I avoided copying the same data into multiple variables.
- Also I used nan instead of zeros because NaNs will always indicate invalid data, whereas zeros can be perfectly valid data. Therefore using NaNs makes it easier to detect if the loops worked properly or not.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!