save answers for different values used in a while loop in an array of (2,n)
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
David Sanchez
2014-10-15
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 个评论
Harm
2014-10-15
1 个评论
David Sanchez
2014-10-15
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
...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!