Creating matrix nested for loop

I need to write a matrix where the first column has the varying mass of an ODE, the second to n-th column all the y(t) values of that ODE. I tried to solve this with a nested for loop but somehow fail so hard eventhough I am sure it is pretty easy.
for row_index = 1:10
for col_index = 1:length(time)
Matrix(row_index,column_index) = [mass(row_index)];
end
end
Somehow something after "[mass(row_index)]" is missing or do you know a way to make it more elegant?
Thanks in advance!

1 Kommentar

Jan
Jan am 24 Okt. 2016
@Detox: Please do not cross-post a question. If it is really important to post a question in different forums, please add at least links to the other forum. Otherwise the voluntary helpers waste time with writing answers, which have been given elsewhere already. Thanks.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Chaya N
Chaya N am 22 Okt. 2016
Bearbeitet: Chaya N am 22 Okt. 2016

0 Stimmen

If you already have all these data available (in separate vectors, I assume) then you do not need any loops.
For example, if you had
x = [all the ODE mass values];
y1 = [values for y(1)]; % at time = 1
y2 = [values for y(2)]; % at time = 2
.
.
.
yt = [values for y(t)]; % at some time 't'
you could do:
matrix = [x y1 y2 ... yt]; if all of these are column vectors and of the same length
or
matrix = [x; y1; y2; ...; yt]'; if all of these are row vectors of the same length
NOTE: Please observe the differences in syntax between the two versions!

4 Kommentare

Detox
Detox am 22 Okt. 2016
Bearbeitet: Detox am 22 Okt. 2016
Thanks for your answer. But I want to solve this Problem with a nested loop if possible. Any ideas on How i could Achieve that?
Chaya N
Chaya N am 22 Okt. 2016
Bearbeitet: Chaya N am 22 Okt. 2016
Alright! Here is a simple illustration. Assume that your ODE mass values are represented by 'x', your y(t) functions are represented by the anonymous function 'y', time values are contained in 't' and the final matrix is called 'm'.
x = 1:10;
y = @(x,t) x*t^2; % just an example
t = 1:10;
m = [x' zeros(numel(x),numel(t))]; % preallocate and fill in first column with 'x'
for r = 1:numel(x) % row counter
for c = 1:numel(t) % column counter
m(r,c+1) = y(x(r),t(c)); % note the 'c+1' column subscript for the output matrix
end
end
Chaya N
Chaya N am 22 Okt. 2016
If you still have trouble, please also include your equation for y(t) when you post here.
Function is:
function ydot = Exp_01(t,y,m)
ydot = zeros(size(y));
ydot(1) = y(2);
ydot(2) = (-y(2)-100*y(1))./m;

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 22 Okt. 2016

Kommentiert:

Jan
am 24 Okt. 2016

Community Treasure Hunt

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

Start Hunting!

Translated by