0

For part of my Statics homework, I have to create a MATLAB function that will take "n" forces acting on a system and turn them into an nx3 matrix. Yes, the "n"s are intentional, the amount of rows is supposed to change with the amount of forces. From there, I need to be able to make it an augmented matrix and solve, for a resultant force, yada yada...I just have no clue where to start setting up a matrix with an unknown amount of rows. Any help would be appreciated, thanks.

1 Answers1

1

If you can avoid creating the matrix until you know the value of n then you should. At that stage you'd just allocate it doing

mat = nan(n,3);  % or zeros(n,3) if you'd prefer.

And then change the elements doing

mat(row_to_change,:) = new_1_by_3_values;

However, if you really need to dynamically resize the matrix - which is sometimes required, but should be avoided if possible for efficiency reasons - then you'd initialize the variable using,

mat = []; % empty matrix

and then anytime you want to append new data to the matrix you can do either

mat = [mat; new_1_by_3_values];

or

mat(end+1,:) = new_1_by_3_values;
Phil Goddard
  • 10,571
  • 1
  • 16
  • 28
  • 4
    Please don’t recommend `mat = [mat; new_1_by_3_values]`, it is highly inefficient. The other form (`end+1`) is the correct one. The difference is not minor. It is huge! See this Q&A pair to understand the difference: https://stackoverflow.com/questions/48351041/matlab-adding-array-elements-iteratively-time-behavior – Cris Luengo Oct 13 '19 at 18:57