Find min value of each column of 2D lattice and plot
4 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Dyuman Joshi
2023-3-16
编辑:Dyuman Joshi
2023-3-16
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)
[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)
scatter(1:n,n+1-ctr,'G','filled')
更多回答(1 个)
Mathieu NOE
2023-3-16
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
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!