finding minimum from two matrix

2 views (last 30 days)
jano satti
jano satti on 13 Sep 2017
Answered: Deepak on 1 Jul 2023
I have matrix A and B of same order. I want to find minimum nonzero value of matrix A and its location. If A has more than one same minimum values than minimum should be selected from B matrix from the given location of matrix A. How I get one minimum value from matrix A and B and its lOcation in a loop. Thanks

Answers (1)

Deepak
Deepak on 1 Jul 2023
As per your query, you can find the minimum value of matrix A and the minimum value of matrix B at those locations using the following method -
A = [1 0 3; 2 0 5; 0 4 0];
B = [7 8 9; 6 5 4; 3 2 1];
% Initialize the minimum value and its location
minValueA = Inf;
minLocationA = [0, 0];
% Loop through each element of matrix A
[row, col] = size(A);
for i = 1:row
for j = 1:col
% Check if the element is nonzero and smaller than the current minimum
if A(i, j) ~= 0 && A(i, j) < minValueA
% Update the minimum value and its location
minValueA = A(i, j);
minLocationA = [i, j];
end
end
end
% Initialize the minimum value from matrix B
minValueB = Inf;
% Loop through each element of matrix A again
for i = 1:row
for j = 1:col
% Check if the element of A is equal to the minimum value of A
if A(i, j) == minValueA
% Check if the corresponding element in B is smaller than the current minimum
if B(i, j) < minValueB
% Update the minimum value from matrix B
minValueB = B(i, j);
end
end
end
end
% Display the minimum value of A, its location, and the minimum value of B
disp("Minimum Value of A: " + minValueA);
disp("Location in A: " + minLocationA);
disp("Minimum Value of B at the location: " + minValueB);

Categories

Find more on Creating and Concatenating Matrices 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!