subset a matrix based on column names in matlab

To subset a matrix in MATLAB based on column names, you can use the following code:

main.m
% create a sample matrix
matrix = [1 2 3; 4 5 6; 7 8 9];
column_names = {'A', 'B', 'C'};

% extract columns of interest
cols_of_interest = {'A', 'C'}; % choose the columns you want to extract
col_idx = ismember(column_names, cols_of_interest); % get the index of columns of intereset
sub_matrix = matrix(:, col_idx); % create your subset matrix 

% display results
disp('Original Matrix:')
disp(matrix)
disp('Columns of Interest:')
disp(cols_of_interest)
disp('Subset Matrix:')
disp(sub_matrix)
495 chars
17 lines

In this code, we create a sample matrix and a cell array of column names. We then choose the columns we want to extract using the cols_of_interest variable. Using the ismember function, we find the indeces of columns that we want to extract. Finally, we create a subset matrix using only the columns we wanted.

related categories

gistlibby LogSnag