Assign different values per column using logical indexing
Show older comments
I am new to logical indexing and am having some trouble with a specific issue. I want to use logical indexing to assign a certain value to all values in a column where the condition is true, and then a different value to the next column where another condition is true at the same time. E.g.:
matrix = magic(5); % data matrix
boundary_conditions = [10, 100]; % boundary conditions
matrix(matrix(:, [2,3]) < boundary_conditions) = boundary_conditions; % use logical indexing to set values of time columns
Essentially, I want to find which values in column 2 are below 10, and which values in column 3 are below 100. Then, those that are in column 2, set them to 10, and those that are in column 3, set to 100. And have that reflected in the original matrix, so only columns 2 and 3 are changed.
For some context:
I am working on a molecular dynamics simulation, so I want to check after each timestep whether a particle has passed the boundary in the x- or y- direction.
Because of this, performance is a necessity, since I am working with ~3,000,000 time iterations. So I want to maximize my efficiency.
Accepted Answer
More Answers (1)
A simpler approach for your task would be
matrix = magic(5) % data matrix
matrix(:,2) = max(matrix(:,2),10)
matrix(:,3) = max(matrix(:,3),100)
If you have to do this for some specific columns or all the columns (for which manually doing that would be a tedious task) you can integrate a for loop.
%For example
matrix = magic(5)
s = size(matrix,2);
boundary_conditions = randi([10 20],1,s)
for k=1:s
matrix(:,k) = max(matrix(:,k),boundary_conditions(k));
end
matrix
5 Comments
Jose Pratdesaba
on 27 Sep 2023
That depends on the data you have.
One approach would be -
arr = magic(9)
%Random values for example
x = randi(9)
%columns for which values to compare and change
idx = randperm(9,x)
%boundary conditions
val = randi([50 100],1,numel(idx))
for k=1:x
arr(:,idx(k)) = max(arr(:,idx(k)),val(k));
end
arr
For the same data, using Voss's vectorized approach -
arr = magic(9);
x = 5;
idx = [8 4 3 7 5];
val = [67 73 55 61 89];
arr(:,idx) = max(arr(:,idx),repmat(val,size(arr,1),1))
Jose Pratdesaba
on 27 Sep 2023
Dyuman Joshi
on 27 Sep 2023
You are welcome!
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!