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

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

답변 (2개)

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
Harm 2014년 10월 15일
thanks David,
A little additional question:
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

댓글 수: 1

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
...

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2014년 10월 15일

댓글:

2014년 10월 15일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by