save answers for different values used in a while loop in an array of (2,n)
2 views (last 30 days)
Show older comments
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:
function [answerarray]=opgave30c2(d)
for plocation=1:d
iter=1;
pnew=[];
k=1;
p=plocation;
r=rem(p,2);
amountofsteps=1;
answerarray=zeros(2,d);
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;
answerarray(1,plocation)=index;
answerarray(2,plocation)=highestvalue;
clear m n pnew p aantalstappen iter highestvalue plocation
end;
% disp(aantalstappen);
% disp(pnew);
% disp(highestvalue);
% disp(index);
% disp(p);
Could you guys please help me out?
Thanks!
H
0 Comments
Answers (2)
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.
0 Comments
Harm
on 15 Oct 2014
1 Comment
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;
answerarray=zeros(2,d);
while (p>k)
if (r==0)
pnew(iter)=p/2;
elseif (r>0)
pnew(iter)=p*3+1;
end
...
See Also
Categories
Find more on Loops and Conditional Statements 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!