Help with using "While Loop"

15 views (last 30 days)
Nicholas
Nicholas on 16 Oct 2015
Answered: Walter Roberson on 17 Oct 2015
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 Comments
per isakson
per isakson on 16 Oct 2015
  • "adding 20 to each element" &nbsp I cannot spot "20" in the code
  • otherwise is legal only in the switch statement
Nicholas
Nicholas on 17 Oct 2015
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.

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 16 Oct 2015
Hint
while k < numel(A)
if A(k) .........
elseif
end
k = k + 1;
end
  2 Comments
Nicholas
Nicholas on 17 Oct 2015
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 on 17 Oct 2015
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.

Sign in to comment.


Walter Roberson
Walter Roberson on 17 Oct 2015
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

Categories

Find more on Data Type Conversion 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!