How to get data from 2D array and put into 1D array

后端 未结 3 411
眼角桃花
眼角桃花 2021-01-27 14:44

I have a 2D array and I want to create a 1D by MATLAB, satisfying the requirement that each element of the 1D output was created by the value of a given index into the 2D array.

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-27 15:21

    You can use cellfun to do it. You convert A into cell by column, and execute f for each element of the cell.

     A=[2 4 6; 1 2 7];
    
     % some example f funcion that just adds the col_index_A and row_index_A
     f = @(col_index_A, row_index_A) col_index_A + row_index_A; 
    
     % execute f with parameters that come from each column of A
     B = cellfun(@(c) f(c(1), c(2)), num2cell(A, 1));
    
     B =
    
         3     6    13
    

提交回复
热议问题