How do I stoop overwriting the variable in a "for" loop?
조회 수: 6 (최근 30일)
이전 댓글 표시
Hi, I'm using the following code:
for i=1:nbs.NBS.n
global nbs;
adj=nbs.NBS.con_mat{i}+nbs.NBS.con_mat{i};
adj=full(adj)
end
nbs.NBS.n = 21 so it iterates 21 times through it, so far so good. However every time it overwrites the variable "adj". What I would like it to do is create adj_1 to adj_21, How can I do that?
I tried typing adj{i}... and adj.(i).... both don't work. Any ideas please?
Thanks
댓글 수: 0
답변 (2개)
David Sanchez
2013년 5월 23일
Try this out:
adj = zeros(nbs.NBS.n,1); % initialize the variable
for i=1:nbs.NBS.n
global nbs;
adj=nbs.NBS.con_mat{i}+nbs.NBS.con_mat{i};
adj(i)=full(adj)
end
댓글 수: 2
David Sanchez
2013년 5월 23일
You can try with a cell array as well.
adj = cell(nbs.NBS.n,1); % initialize the variable as a cell array
for i=1:nbs.NBS.n
global nbs;
adj=nbs.NBS.con_mat{i}+nbs.NBS.con_mat{i};
adj{i}=full(adj)
end
Matt J
2013년 5월 23일
편집: Matt J
2013년 5월 23일
I tried typing adj{i}... and adj.(i).... both don't work. Any ideas please?
Works fine for me. Not sure why you have "global nbs" in the for-loop, though.
nbs.NBS.n=21;
nbs.NBS.con_mat=num2cell(1:21);
for i=1:nbs.NBS.n
global nbs
adj{i}=nbs.NBS.con_mat{i}+nbs.NBS.con_mat{i};
adj{i}=full(adj{i});
end
adj =
Columns 1 through 14
[2] [4] [6] [8] [10] [12] [14] [16] [18] [20] [22] [24] [26] [28]
Columns 15 through 21
[30] [32] [34] [36] [38] [40] [42]
댓글 수: 2
Matt J
2013년 5월 24일
편집: Matt J
2013년 5월 24일
In my version it does that, but it overwrites the existing adj variable. I would like it to create new adj variables for each cell rather than overwriting the existing one...
Then basically, you're just trying to convert all your matrices from sparse to full form? Anyway, how is that different from having adj{i}, i=1...21 like what the code I gave you produces? Each adj{i} does behave like a separate variable.
참고 항목
카테고리
Help Center 및 File Exchange에서 Specifying Target for Graphics Output에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!