Convert the row of a matrix into a vector
2 views (last 30 days)
Show older comments
Hello everybody.
I have my matrix "A" wich the user define its size, for example, the user define a size 3x5 for the matrix A:
[1 2 3 4 5]
A= [2 4 6 8 3]
[2 4 5 7 8]
I need to convert the rows into new vectors like this:
A1=[1 2 3 4 5]
A2=[2 4 6 8 3]
A3=[2 4 5 7 8]
But the problem is that, as the user can modify the size of the matrix (adding/deleting rows), I need to take the vectors. For example, the user define a new size of the matrix A as 5x5, so I need
A1=[...]
A2=[...]
...
A5=[...]
I would not like to manually put the new vectors because the number of rows may become too large (around 500 or more) and put each new vector manually it becomes almost impossible. So I need that MatLab do this automatically.
Thank You.
0 Comments
Answers (2)
Star Strider
on 26 Dec 2015
Adding rows to a matrix is easy enough. There are several ways, one of which is the cat function. If you want to append vector ‘V’ to matrix ‘A’ using it, you would define the new ‘A’ as:
A = cat(1, A, V);
Defining the elements of ‘V’ appears to be the problem, however. How do you want to define the new row? Can the elements of it be random, or is there some rule you want to use to define them?
4 Comments
Star Strider
on 26 Dec 2015
If all you want to do is print them to a file or to the Command Window, that is straightforward:
A = [1 2 3 4 5
2 4 6 8 3
2 4 5 7 8
4 5 6 6 7
8 2 3 3 1];
v = 1:size(A,1); % Define Rows
Rows = sprintf(['A%d = [ ' repmat('%.0f ', 1, size(A,2)) ']\n'], [v' A]')
Rows =
A1 = [ 1 2 3 4 5 ]
A2 = [ 2 4 6 8 3 ]
A3 = [ 2 4 5 7 8 ]
A4 = [ 4 5 6 6 7 ]
A5 = [ 8 2 3 3 1 ]
You don’t even need a loop. This keeps them in your workspace as a string variable, ‘Rows’.
To print them to a file, see the documentation for the fprintf function. The essence of the code remains the same, but you have to define a file and a file identification number for it to print to.
Image Analyst
on 26 Dec 2015
This will display what you asked for:
% Create sample data.
A=[1 2 3 4 5;...
2 4 6 8 3;...
2 4 5 7 8;...
4 5 6 6 7;...
8 2 3 3 1]
% Display the desired rows in the specified format
for row = 1 : size(A, 1)
fprintf('A%d = [', row);
fprintf('%d ', A(row,:));
fprintf(']\n');
end
It does not create 5 or 500 new row vectors - there is no need for that that I can see. Why on earth would you want that? I mean, why would you deliberately want to go against the recommendations in the FAQ? http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
0 Comments
See Also
Categories
Find more on Analog Devices ADALM1000 Support from Data Acquisition Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!