简体   繁体   中英

Treat each row of a matrix as a vector in a MATLAB function

Say I have a nxm matrix and want to treat each row as vectors in a function. So, if I have a function that adds vectors, finds the Cartesian product of vectors or for some reason takes the input of several vectors, I want that function to treat each row in a matrix as a vector.

This sounds like a very operation in Matlab. You can access the ith row of a matrix A using A(i, :) . For example, to add rows i and j , you would do A(i, :) + A(j, :) .

Given an nxm matrix A:

  1. If you want to edit a single column/row you could use the following syntax: A(:, i) for the ith-column and A(i, :) for ith-row.
  2. If you want to edit from a column/row i to a column/row j, you could use that syntax: A(:, i:j) or A(i:j, :)
  3. If you want to edit (ie) from the penultimate column/row to the last one, you could you: A(:, end-1:end) or A(end-1:end, :)

EDIT: I can't add a comment above because I don't have 50 points, but you should post the function setprod. I think you should be able to do what you want to do, by iterating the matrix you're passing as an argument, with a for-next statement.

I think you're going to have to loop:

Input

M = [1 2; 
     3 4; 
     5 6];

Step 1: Generate a list of all possible row pairs (row index numbers)

n = size(M,1);
row_ind = nchoosek(1:n,2)

Step 2: Loop through these indices and generate the product set:

S{n,n} = []; //% Preallocation of cell matrix
for pair = 1:size(row_ind,1)
    p1 = row_ind(pair,1);
    p2 = row_ind(pair,2);
    S{p1,p2} = setprod(M(p1,:), M(p2,:))
end

Transform the matrix into a list of row vectors using these two steps:

  1. Convert the matrix into a cell array of the matrix rows, using mat2cell .
  2. Generate a comma-separated list from the cell array, using linear indexing of the cell contents.

Example: let

v1 = [1 2];
v2 = [10 20];
v3 = [11 12];
M = [v1; v2; v3];

and let fun be a function that accepts an arbitrary number of vectors as its input. Then

C = mat2cell(M, ones(1,size(M,1)));
result = fun(C{:});

is the same as result = fun(v1, v2, v3) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM