change length to match row and columns in matlab

To change the length of a matrix to match a certain number of rows and columns in MATLAB, you can use the reshape function.

For example, let's say you have a vector with 12 elements and want to reshape it into a 3x4 matrix:

main.m
% create a 1x12 vector
v = 1:12;

% reshape the vector into a 3x4 matrix
m = reshape(v, 3, 4);
95 chars
6 lines

When you call reshape(v, 3, 4), MATLAB will take the first 3 elements of v and put them into the first row of m, the next 3 elements and put them into the second row of m, and so on until all elements of v have been used to fill m.

You can also use this same syntax to reshape matrices of any size as long as the number of elements in the matrix matches the number of elements in the new matrix size. If the number of elements does not match, MATLAB will throw an error.

related categories

gistlibby LogSnag