# save answers for different values used in a while loop in an array of (2,n)

2 views (last 30 days)
Harm on 15 Oct 2014
Commented: David Sanchez on 15 Oct 2014
the question is how to save the highest value of vector pnew(highestvalue) and the location of this highest value in the vector pnew (index) in a matrix of the size (2,plocation)?
I get the right values for column p when i only apply a while loop.
function [amountofsteps, pnew, highestvalue, index]=exercise30b(p)
iter=1;
pnew=[];
k=1;
r=rem(p,2);
amountofsteps=1;
while (p>k)
if (r==0)
pnew(iter)=p/2;
elseif (r>0)
pnew(iter)=p*3+1;
end;
p=pnew(iter);
r=rem(p,2);
amountofsteps=amountofsteps+1;
iter=iter+1;
[index, highestvalue]=max(pnew);
end;
disp(amountofsteps);
disp(pnew);
disp(highestvalue);
disp(index);
now i want to apply a for loop to derive the same for different values of p. Unfortunately, I get an error that "index" and "highest value" are undefined variables when i want to accomodate them into the array. please see below:
for plocation=1:d
iter=1;
pnew=[];
k=1;
p=plocation;
r=rem(p,2);
amountofsteps=1;
while (p>k)
if (r==0)
pnew(iter)=p/2;
elseif (r>0)
pnew(iter)=p*3+1;
end;
p=pnew(iter);
r=rem(p,2);
amountofsteps=amountofsteps+1;
iter=iter+1;
highestvalue=max(pnew);
index = find(pnew == max(pnew), 1);
end;
clear m n pnew p aantalstappen iter highestvalue plocation
end;
% disp(aantalstappen);
% disp(pnew);
% disp(highestvalue);
% disp(index);
% disp(p);
Thanks!
H

David Sanchez on 15 Oct 2014
In your second function, you defined
k=1;
and the condition in the while loop is
while (p>k)
which is not fulfilled for any p>1. Then, neither index nor highestvalue get to be defined within the while loop and by extension, within the function.

Harm on 15 Oct 2014
thanks David,
I get the (2,d) array, the only thing what now is left is that the right values should get on the right position in the array.
I filled in d=4. I get only values in the last column. How can i adjust my code to get values in every column?
>> opgave30c2(4)
ans =
0 0 0 1
0 0 0 2
Thanks
David Sanchez on 15 Oct 2014
Initialize outside the for loop:
iter=1;
pnew=[];
for plocation=1:d
k=1;
p=plocation;
r=rem(p,2);
amountofsteps=1;
while (p>k)
if (r==0)
pnew(iter)=p/2;
elseif (r>0)
pnew(iter)=p*3+1;
end
...