How to store values from a loop in a matrix

Im running a simulation in Simscape Multibody that is outputting the velocities in a 199x1 double (called velocity). Im then changin one of the variables 25 times, in a loop and i want to get a big matrix at the end that will output all of the velocites in one place. This is my current code:
%% landing velocity
%initialise matrix
landing_velcity=[];
for i = 1:25
c=9200;
M=300+(100*i);
system=sim ('dropping.slx');
landing_velocity(i)=velocity
end
The error I'm getting is that the left and right sides have different elements.

Answers (1)

Adam Danz
Adam Danz on 13 Apr 2020
Edited: Adam Danz on 14 Apr 2020
Pre-allocate your loop variable according to the number of loops and the length of the variable being stored. Here's an example.
landing_velocity = nan(25, numel(velocity)); % updated to fix typos
for i = 1:25
. . .
landing_velocity(i,:)=velocity;
end

2 Comments

landing_velocity = nan(25, numel(velocity)); % 2 corrections

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 13 Apr 2020

Commented:

on 14 Apr 2020

Community Treasure Hunt

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

Start Hunting!