How to compare terms in column and set an if loop

I'm trying to do lexicographic rule on my matrix and I end up getting a column where two elements are the same. I need to set up an if loop for such an instance where two terms in the column are the same and I have to select one of them based on the index. What would be the code in this case
For example,
I got (5;3;3) as my column vector. If the terms are unique I could use the minimum function to capture the desired row. Otherwise I should choose the variable with the minimum value with another supporting condition. How do I formulate a loop in this case?

Answers (2)

You can find the difference and check when it is equal to zero and get its index.
X = [1 2 3 3 4 5 6] ;
d = find(diff(X)==0)
d = 3
X([d d+1])
ans = 1×2
3 3
Here is one way to pick the minimum value from each column, with space for you to write your own additional code in case of multiple elements in a column sharing the minimum value:
A = magic(6); % some matrix
A_min = min(A,[],1); % A_min is the minimum of each column of A
for i = 1:numel(A_min)
idx = find(A(:,i) == A_min(i)); % find the rows of column i whose element is equal to the minimum element of column i
if numel(idx) == 1
% there is one and only one minimum in column i, located at row idx
continue
end
% multiple elements of column i have the minimum value.
% they are located at rows idx(1), idx(2), etc.
% your code to pick among them goes here
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 13 Dec 2021

Answered:

on 13 Dec 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!