Clear Filters
Clear Filters

Find min value of each column of 2D lattice and plot

3 views (last 30 days)
Hey everyone,
I am looking to create a 10 x 10 lattice with randomly assigned values for each coordinate then find the minimum value of each column of the lattice and finally plotting the lattice with the lowest number of each column coloured to show visually.
so far all I have is this:
clc
clear
P = randi(10, 10, 10);
for i = 1:1:10
[row(i), column(i)] = min(P(:,i));
[x,y] = meshgrid(1:10,1:10);
xlim([1,10])
ylim([0,10])
axis equal
x_l = reshape(x,[],1);
y_l = reshape(y,[],1);
figure; scatter(x_l,y_l)
hold on
scatter(x_l(row(i)),y_l(column(i)), 'R', 'filled')
end
but as you can tell, it doesn't work.
I hope this makes sense!
Thanks

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 16 Mar 2023
Edited: Dyuman Joshi on 16 Mar 2023
It is better to define variables not varying with the loop index, out of the loop. Moreso, as you are using figure().
It's not clear to me, if you want to color the minimum value or the index of the minimum value in each column. The code below corresponds to coloring the minimum value of each column.
Edit - Clarification below in the comments to color the index (first occurance) of the minimum value.
n=10;
P = randi(n, n, n)
P = 10×10
4 4 5 10 6 1 8 1 9 5 9 10 6 7 3 10 10 1 4 1 5 10 4 7 6 10 3 7 1 10 1 7 4 1 8 3 3 8 8 10 6 8 1 1 2 1 6 1 10 8 4 1 7 9 10 6 6 9 8 7 7 5 6 4 5 2 4 7 1 4 2 10 9 2 1 6 6 1 7 3 7 2 4 3 4 4 10 1 8 5 10 5 6 10 7 10 2 1 7 5
[x,y] = meshgrid(1:n);
x_l = reshape(x,[],1);
y_l = reshape(y,[],1);
figure; scatter(x_l,y_l)
xlim([1,n])
ylim([0,n])
axis equal
xticks(1:n)
for i = 1:n
[~,idx] = min(P(:,i));
hold on
scatter(i,n+1-idx, 'R', 'filled')
end
You can achieve the result without the loop as well (As Rik mentioned below)
figure
scatter(x_l,y_l)
xlim([1,n])
ylim([0,n])
axis equal
xticks(1:n)
hold on
%directly obtain the indices
[~,ctr]=min(P)
ctr = 1×10
4 6 5 4 8 1 10 1 3 2
scatter(1:n,n+1-ctr,'G','filled')
  5 Comments
James Kosiol
James Kosiol on 16 Mar 2023
Excellent work! exactly what I was after. Many thanks.

Sign in to comment.

More Answers (1)

Mathieu NOE
Mathieu NOE on 16 Mar 2023
not sure if I understood really what you want to do
maybe this ?
clc
clear
N = 10;
[x,y] = meshgrid(1:N,1:N);
xlim([1,N])
ylim([0,N])
axis equal
x_l = reshape(x,[],1);
y_l = reshape(y,[],1);
figure(1); scatter(x_l,y_l)
for i = 1:N
P = randi(N, N);
[m, ind] = min(P,[],'all','linear');
[r,c] = ind2sub(size(P),ind);
hold on
pause(0.4)
scatter(r,c, 'R', 'filled')
end
  1 Comment
James Kosiol
James Kosiol on 16 Mar 2023
Thanks for your answer, but it is not what I am looking for. Very close though, please see my pictures in the prior comments.

Sign in to comment.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!