I am trying to create a grid in MATLAB.

The number of rows and columns for the grid are to be entered by the user during run-time.

When the user clicks on a particular block/square of the grid,

  1. I need to obtain the co-ordinates of the block (i.e. (1,1), (2,3) etc.)

  2. I also need to color that square/block.

Any suggestions as to how I can do so?

有帮助吗?

解决方案

That may serve as a starter:

% draw a rectangle
% store coordinates in the userdata
r = rectangle('Position', [1 1 1 1], 'UserData', [1,1], 'FaceColor', 'r');
% set the clicked-callback:
set(r, 'ButtonDownFcn', @showIndex);

function showIndex(hObject, evt)
    disp('Clicked on:');
    disp(get(hObject, 'UserData'));
end

[Code syntax edited]

EDIT:

Concerning the coordinates: You can of course use your own coordinates, presumably you get a loop similar to this:

for ix=1:n % loop over columns
    for iy=1:m % loop over rows
        % modify coordinates to your needs
        % e.g. to make the y-index start at 1 from top to bottom:
        coords = [ix,m-iy+1]; 
        r(ix,iy) = rectangle('Position', [ix,iy,1,1], 'UserData', coords, ...);
        % remaining stuff...
    end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top