How do I stoop overwriting the variable in a "for" loop?
4 views (last 30 days)
Show older comments
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 Comments
Answers (2)
David Sanchez
on 23 May 2013
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 Comments
David Sanchez
on 23 May 2013
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
on 23 May 2013
Edited: Matt J
on 23 May 2013
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 Comments
Matt J
on 24 May 2013
Edited: Matt J
on 24 May 2013
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.
See Also
Categories
Find more on Sparse Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!