Help with using "While Loop"

11 次查看(过去 30 天)
Nicholas
Nicholas 2015-10-16
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
per isakson 2015-10-16
  • "adding 20 to each element" &nbsp I cannot spot "20" in the code
  • otherwise is legal only in the switch statement
Nicholas
Nicholas 2015-10-17
Thank you for catching that. Not sure how I missed the 20. Accidentally typed out the matrix again instead of 20. I also didn't know that otherwise only works for switch. I appreciate the help! I replaced otherwise with elseif instead, and I still receive the same error, but regarding elseif instead.

请先登录,再进行评论。

回答(2 个)

Image Analyst
Image Analyst 2015-10-16
Hint
while k < numel(A)
if A(k) .........
elseif
end
k = k + 1;
end
  2 个评论
Nicholas
Nicholas 2015-10-17
I know the general format for while statement, but did not realize that otherwise was only valid for switch statements as the other comment mentioned. Having replaced otherwise with elseif, I am still receiving the same error but regarding elseif instead of otherwise. The part of this I find confusing is that it is dealing with a matrix, so I am having a hard time relating the matrix into the general format.
Image Analyst
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
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by