matrix from arrays of different size
Show older comments
Hi,
I have a for loop in which i solve a system of ode's. The solution looks fine when I plot however I need to save the data at each iteration in one single matrix.
The code is below:
for q=1:20
tspan1=q:21;
[s x] = ode23s(@odebatch,tspan1, [q n0(q) 0],[], h,gr) ;
f=x(:,3);
% xmat(:,q)=padcat(x(:,3)) ;
% u=x(:,1); % % hold on % figure(1) % % plot(f,u)
end
As you can see the time over which the solution to the system of ode is to be found is changing. That means i have arrays of different sizes at each iteration. I want to have something like:
0 NAN 1 0 2 1 3 2 4 3
Any ideas how to do this?
Answers (1)
I don't understand where
0 NAN 1 0 2 1 3 2 4 3
is coming from, but why do you need to have results in a single array? If you just want to store them, use a cell array, e.g.
results = cell(20, 1) ;
for q = 1 : 20
tspan1 = q : 21 ;
[s, x] = ode23s(@odebatch, tspan1, [q, n0(q), 0], [], h, gr) ;
results{q} = [s, x] ;
end
If you really needed to have them in the same array, you could go for something like (not tested):
xmat = nan(21, 20) ; % or xmat = zeros(21, 20) ;
for q = 1 : 20
tspan1 = q : 21 ;
[s, x] = ode23s(@odebatch, tspan1, [q, n0(q), 0], [], h, gr) ;
xmat(q:21,q) = x(:,3) ;
end
2 Comments
Graham
on 13 May 2013
Starting with a side note, be careful with i and j, they are "reserved" (even if everybody uses them) to complex notation. We usually use ii and jj instead for indexing.
The reason your code doesn't work is that you are using a q that goes from 1 to an upper boundary by steps of 500, for indexing columns in xmat (whereas column indices should not evolve by steps of 500). You should have something like the following instead, where the loop index can be used for indexing columns and picking the relevant lower boundary:
uBnd = ... ; % Upper boundary.
lBnds = 1 : 500 : uBnd-1 ; % Lower boundaries (-1 ?).
n = length(lBnds) ; % Number of lBnds and runs.
xmat = nan(uBnd, n) ; % Prealloc/fills xmat with nans.
for k = 1 : n
lBnd = lBnds(k) ; % Formerly named 'q'.
tspan1 = lBnd : uBnd ;
[s, x] = ode23s(@odebatch, tspan1, [lBnd, n0(lBnd), 0], [], h, gr) ;
xmat(tspan1,k) = x(:,3) ;
end
The first version of the code was working (I guess) in your first situation, because q used as a loop index (1:20) could also be used as a column index.
Categories
Find more on Matrix Indexing 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!