Skip to content

Instantly share code, notes, and snippets.

@bbrrck
Last active May 7, 2018 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbrrck/2f4018d7ecf338330d3bba2c0835dcbd to your computer and use it in GitHub Desktop.
Save bbrrck/2f4018d7ecf338330d3bba2c0835dcbd to your computer and use it in GitHub Desktop.
Matlab: replace indices in a matrix
%% test data
% random seed
rng(1234567890);
% vector of original indices
A = (101:110)';
% random vector of new indices
% same length as A, can have duplicates
B = randi([1 10],length(A),1);
% random matrix with indices from A
MA = randi(A([1 end]),10,3);
%% in MA, replace A(i) by B(i)
% find positions of indices from A in MA
[check,mask] = ismember(MA,A);
% make sure all values have been found
assert(all(check(:)));
% replace
MB = B(mask);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment