필터 지우기
필터 지우기

Plotting multiple outputs of a function through a For loop

조회 수: 2 (최근 30일)
Emma Humphrey
Emma Humphrey 2018년 8월 21일
편집: Emma Humphrey 2018년 8월 24일
I am trying to plot the outputs of a function in my main through a For loop. I define the function (ballMC) in a separate m-file, and then call it to my main with specified inputs defined through the For loop. I tried to map the results of the For loop into an array, but I ended up getting the following message 'Array indices must be positive integers or logical values.' In the two lines of code before ending the loop. Any insight would be very much appreciated.
My code is as follows
n=2
Resultsestimate= zeros(50,1, 'double');
Resultshalfwidth =zeros(50,1, 'double');
for Nreps=logspace(1,6);
[estimate, halfwidth]=ballMC(Nreps,n);
Resultsestimate(Nreps)= estimate;
Resultshalfwidth(Nreps)= halfwidth;
end
figure(1)
plot(Nreps,Resultsestimate)
figure(2)
plot(Nreps,Resultshalfwidth)
  댓글 수: 4
Stephen23
Stephen23 2018년 8월 22일
@ADragon: you should move your comment to an answer.
ADragon
ADragon 2018년 8월 22일
Hi Stephen, you are right. Thanks!

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

채택된 답변

ADragon
ADragon 2018년 8월 22일
It does not appear that Nreps is an integer value that can be used as an array index. You could try:
Nreps = logspace(1,6);
for i = 1:length(Nreps)
[estimate, halfwidth]=ballMC(Nreps(i),n);
Resultsestimate(i)= estimate;
Resultshalfwidth(i)= halfwidth;
end
Or with fewer intermediate variables:
Nreps = logspace(1,6);
for i = 1:length(Nreps)
[Resultsestimate(i), Resultshalfwidth(i)] = ballMC(Nreps(i),n);
end
I would also initialize your result vectors too before the for loop (the code analyzer likes this).
  댓글 수: 2
Stephen23
Stephen23 2018년 8월 22일
+1 clear and useful answer
Emma Humphrey
Emma Humphrey 2018년 8월 24일
편집: Emma Humphrey 2018년 8월 24일
ADragon thank you very much for your answer , it completely works now.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by