Help with using "While Loop"
이전 댓글 표시
Hello,
I am trying to figure out how to do a problem using the "while" command. The instructions on the problem are:
Consider the array A
A = [3, 5, -4; -8, -1, 33; -17, 6, -9]
Write a program that computes the array B by computing the natural logarithm of all elements in A whose value is no less than 1, and adding 20 to each element that is equal to or greater than 1.
- a.) Using a "for" loop
- b.) Using a "while" loop.
I have already completed part a, but part b is giving me some troubles. Here is what I have so far:
clc, clear all, format compact
A = [3, 5, -4; -8, -1, 33; -17, 6, -9];
m = 1:size(A,1);
n = 1:size(A,2);
while A(m,n) >= 1;
A(m,n) = A(m,n) + log(A(m,n));
otherwise A(m,n) = A(m,n);
end
disp(A)
I am getting the error "Illegal use of reserved keyword "otherwise". when I am running the script. By removing the "otherwise" portion, it just gives me the original array A.
Any help would be very much appreciated!
Thanks,
Nick
댓글 수: 2
per isakson
2015년 10월 16일
- "adding 20 to each element"   I cannot spot "20" in the code
- otherwise is legal only in the switch statement
Nicholas
2015년 10월 17일
답변 (2개)
Image Analyst
2015년 10월 16일
Hint
while k < numel(A)
if A(k) .........
elseif
end
k = k + 1;
end
댓글 수: 2
Nicholas
2015년 10월 17일
Image Analyst
2015년 10월 17일
Make it easy for us to help you, not hard. I don't have the Mind Reading Toolbox yet so I don't know the current state of your code. Please post all your code, and all the red text - don't snip out or paraphrase any of it.
Walter Roberson
2015년 10월 17일
When you have a loop which is
for n = 1 : Value
some code
end
then you can replace it with
n = 1;
while n <= Value
some code
n = n + 1;
end
카테고리
도움말 센터 및 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!