f



Converting a nested for loop to a while loop.

I am working on a problem where I need to convert a nested for loop to a while loop.  I've got the problem partially solved but I was only able to get the code to initialize the first row of the Array. Where am I going wrong?

Here is the initial code that I made for the for loop:
A = [3 5 4;-8 -1 33;-17 6 -9];
B = zeros(size(A))
for i = 1:1:size(A,1)
for j = 1:1:size(A,2)
    if(A(i,j) >= 1)
        B(i,j)=A(i,j)+20
    else
        B(i,j)=log(A(i,j))
    end
end
end

Here is what I came up for the while loop:
B = zeros(size(A));
i = 0;
j = 0;
while i < size(A,1)
    i = i+1;
    while j < size(A,2)
        j= j+1;
        if A(i,j)>=1
            B(i,j)=A(i,j)+20
        else
        B(i,j)=log(A(i,j))
        end
    end
end

This is the answer I got for the while loop
B =
    23     0     0
     0     0     0
     0     0     0
B =
    23    25     0
     0     0     0
     0     0     0
B =
    23    25    24
     0     0     0
     0     0     0
0
Russell
10/16/2015 9:54:03 PM
comp.soft-sys.matlab 211264 articles. 26 followers. lunamoonmoon (257) is leader. Post Follow

1 Replies
870 Views

Similar Articles

[PageSpeed] 37


"Russell May" <russellmay@sbcglobal.net> wrote in message 
news:mvrrlr$3e5$1@newscl01ah.mathworks.com...
> I am working on a problem where I need to convert a nested for loop to a 
> while loop.  I've got the problem partially solved but I was only able to 
> get the code to initialize the first row of the Array. Where am I going 
> wrong?
>
> Here is the initial code that I made for the for loop:
> A = [3 5 4;-8 -1 33;-17 6 -9];
> B = zeros(size(A))
> for i = 1:1:size(A,1)
> for j = 1:1:size(A,2)
>    if(A(i,j) >= 1)
>        B(i,j)=A(i,j)+20
>    else
>        B(i,j)=log(A(i,j))
>    end
> end
> end
>
> Here is what I came up for the while loop:
> B = zeros(size(A));
> i = 0;
> j = 0;

Let's add a few lines so you can see the values of your indices each time 
MATLAB executes the loops.

> while i < size(A,1)
>    i = i+1;

fprintf('Before start of WHILE J, i is %d and j is %d\n', i, j);

>    while j < size(A,2)
>        j= j+1;
>        if A(i,j)>=1
>            B(i,j)=A(i,j)+20
>        else
>        B(i,j)=log(A(i,j))
>        end

fprintf('Before end of WHILE J, i is %d and j is %d\n', i, j);

>    end

fprintf('Before end of WHILE I, i is %d and j is %d\n', i, j);

Adding these three status display lines should show you a problem. Moving 
one line of code that you have already written will solve that problem.

*snip*

-- 
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on 
http://www.mathworks.com 

0
Steven
10/19/2015 4:28:42 PM
Reply: