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!