以下是我的代码:
function marks(my_numbers)
handle = zeros(5,1)
x = 10 ;
y = 10:20:100 ;
for i = 1
for j = 1:5 ;
handle(j,i) = rectangle('position',[x(i),y(j),20 10],'facecolor','r')
end
end
end
现在让我们说输入参数my_numbers = 2
所以我写了代码:
set(handle(j(my_numbers),1),'facecolor','g')
使用此命令,(30,10)左下角的矩形应该变为绿色。但MATLAB给出了索引超出矩阵维度的错误
答案 0 :(得分:1)
这是一个插图说明而不是答案,但正如@hagubear提到的那样,i
索引毫无意义,所以你可以完全删除它。
使用set(handle(my_numbers,1),'facecolor','g')
会删除错误,因为您尝试访问handles(j(2),1)
而这是不可能的,因为j
是标量。
无论如何在你的情节工作正常后使用这一行:
set(handle(my_numbers,1),'facecolor','g')
根据您在下面的评论,这里有一种方法可以多次调用该函数并添加绿色矩形。有两个文件用于演示,功能本身和一个脚本多次调用该函数并生成一个GIF动画:
1)功能:
function marks(my_numbers)
%// Get green and red rectangles to access their properties.
GreenRect = findobj('Type','rectangle','FaceColor','g');
RedRect = findobj('Type','rectangle');
%// If 1st call to the function, create your plot
if isempty(RedRect)
handle = zeros(5,1);
x = 10 ;
y = 10:20:100 ;
for j = 1:5 ;
handle(j) = rectangle('position',[x,y(j),20 10],'facecolor','r');
end
set(handle(my_numbers,1),'facecolor','g')
%// If not 1st call, fetch existing green rectangles and color them green. Then color the appropriate rectangle given by my_numbers.
else
RedRect = flipud(RedRect); %// Flip them to maintain correct order
if numel(GreenRect) > 0
hold on
for k = numel(GreenRect)
set(GreenRect(k),'facecolor','g')
set(RedRect(my_numbers,1),'facecolor','g')
end
end
end
2)剧本:
clear
clc
%// Shuffle order for appearance of green rectangles.
iter = randperm(5);
filename = 'MyGifFile.gif';
for k = iter
marks(k)
pause(1)
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if k == iter(1)
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end
以下是输出的动画gif: