Convert rows of a matrix to vectors

后端 未结 1 704
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 07:11

I have a matrix lets say:

A=[1 2 1; 5 6 7; 7 8 9]

and I want to extract its rows in the following format:

x_1=[1 2 1] x_2=[5          


        
相关标签:
1条回答
  • 2021-01-29 07:39

    You can try the following:

    m = size(A,1);
    
    for i=1:m
        % set the variable name
        varName = sprintf('x_%d',i);
    
        % create and assign the variable in the base workspace
        assignin('base',varName,A(i,:));
    end 
    

    The code iterates through every row of A, creates the variable name (as per your format) and then assigns a variable in the MATLAB base workspace ('base') with its data being the ith row of A.

    If doing this from a function, rather than using 'base' use 'caller' to indicate that the variables should be created in the workspace of the function.

    0 讨论(0)
提交回复
热议问题