How do i use a pair of nested for loops to store a series of 9 related numbers in a 3x3 matrix?
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
Stephen23
2019년 1월 27일
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
Stephen23
2019년 1월 27일
편집: Stephen23
2019년 1월 28일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!