Loop output not saving to a cell array. Only last solution saving to cell
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
This question has been asked and I have read the accepted answers. But I just don't get it. Its been several hours working on this now and I'm hoping for some very clear help.
I have a loop with only 6 iterations. Within that loop is a function. Each time the loop runs, the function solves and a solution array of size (20000, 1) is generated. I want to save each solution array for all 6 iterations. But my attempts have resulted in only the last iteration's solution being stored for all cnew{1,1}, cnew{2,1} ... cnew{6,1}. They're all equal in the cnew cell, but I know with 100% certainty that each solution array z is not equal with changing parameter values.
Please help
Below is my code:
for iter=1:6
if iter==1, y=0; end
if iter==2, y=0.15; end
if iter==3, y=0.30; end
if iter==4, y=0.45; end
if iter==5, y=0.60; end
if iter==6, y=0.75; end
z = function( _various inputs that change with y_);
cnew = cell(6,1);
for loopiter = 1:6
cnew{iter}=z;
end
end
채택된 답변
You only need one loop:
vec = 0:0.15:0.75;
cnew = cell(numel(vec),1);
for iter = 1:numel(vec)
y = vec(iter);
cnew{iter} = function( _various inputs that change with y_);
end
댓글 수: 16
The fix to your code is to get rid of the inner loop:
cnew = cell(6,1);
for iter=1:6
if iter==1, y=0; end
if iter==2, y=0.15; end
if iter==3, y=0.30; end
if iter==4, y=0.45; end
if iter==5, y=0.60; end
if iter==6, y=0.75; end
cnew{iter} = function( _various inputs that change with y_);
end
Unfortunately I tried that and z{iter} is empty[] except for z{6,1}. Which is odd, because I put a breakpoint in and noticed that after one iteration, z{1,1} was not empty.
Hi Stephen, thank you for your answer but I fear it is too complicated and I'm not sure what exactly is wrong with my code, that is causing only the last solution array z, to be saved.
And you tossed a vec(k) in there. What is k?
"I fear it is too complicated"
My answer uses only things that you already use: vectors and indexing, plus the colon operator to define a vector of all y values. These are all very basic MATLAB concepts that are covered in the introductory tutorials:
Compare your code carefully with the code I gave in my answer: you will see that my answer does much the same thing, just without using a hard-coded number of loop iterations, making it simpler and more flexible at the same time.
"And you tossed a vec(k) in there. What is k?"
My mistake: I often use k for the loop iterator. I changed this to iter.
"Unfortunately I tried that and z{iter} is empty[] except for z{6,1}. Which is odd, because I put a breakpoint in and noticed that after one iteration, z{1,1} was not empty"
What you tested with a breakpoint was not my code, it was the code you showed in your question.
Hi Stephen, yes I understand that vec(k) is meant to represent the various values of y. But that does not seem to work.
I just get the error
y = vec(k);
Undefined function or variable 'k'.
change vec(k) to vec(iter)
Thanks Walter, I appreciate that.
@Stephen
Unfortunately I tried that and z{iter} is empty[] except for z{6,1}. Which is odd, because I put a breakpoint in and noticed that after one iteration, z{1,1} was not empty"
What you tested with a breakpoint was not my code, it was the code you showed in your question.
That is correct. I tested with a breakpoint on my code. Unfortunately there is not really a way to share with you that I know of. This is my great frustration. Why would only the last solution be saved after all iterations have completed? Perhaps if you know of an explanation, I can troubleshoot.
"Perhaps if you know of an explanation, I can troubleshoot."
I wrote that in the very first sentence of my answer. Read my answer again.
Question: how many loops have I used in my code?
Question: how many loops have you used in your code?
I only need one loop? Is that your solution?
"I only need one loop?"
Yes. Which is why I wrote that in my answer one hour ago.
So I just tried the following and still only the last iteration is saved.
vec=0:0.15:0.75;
z = cell(numel(vec),1);
for iter=1:numel(vec)
y = vec(iter);
[z{iter}] = function( _various inputs that change with y_)
cnew=z{iter};
disp(iter)
end
This should work:
vec = 0:0.15:0.75;
out = cell(numel(vec),1);
for iter = 1:numel(vec)
y = vec(iter);
out{iter} = function( _various inputs that change with y_)
end
If this does not work then please upload the exact code that you are using by clicking the paperclip button. It would also be helpful to upload the function too.
Stephen that did work. Thank you. I would encourage you to use more explanation when you provide solutions because people come here to LEARN. For example, why does it matter to have only one loop?
@EM: The problem with your original code was the two loops:
for iter = 1:6
if iter==1, y=0; end
if iter==2, y=0.15; end
if iter==3, y=0.30; end
if iter==4, y=0.45; end
if iter==5, y=0.60; end
if iter==6, y=0.75; end
z = function( _various inputs that change with y_);
cnew = cell(6,1);
for loopiter = 1:6
cnew{iter}=z;
end
end
Note that the on every iteration of the outper loop you completely redefine cnew, so anything stored in cnew on iterations 1:5 is discarded. That leaves only the final iteration, where y=0.75: on this final iteration you calculate z, redefine cnew again (discarding any existing data), and then use the inner loop to put the same z value into each cell of cnew. Thus cnew only contains the z value from the final outer loop iteration.
Using a breakpoint was a very good idea: step through until the end and you will notice that you redefine cnew on each outer loop iteration, discarding all of the existing data. You will also notice that the inner loop allocates exactly the same z value to all cnew cells.
My answer has one loop, iterating as many times as there are elements in vec. For each element it gets one y value from the vector, calculates the function, and saves the output value in cnew.
Great, that makes sense. Thank you for the explanation. Please save this explanation for any future visitors
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
태그
아직 태그를 입력하지 않았습니다.
참고 항목
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
