Problem assigning multiple values simultaneously to a matrix

1 次查看(过去 30 天)
Hello,
I have attached some code for reference;
flag=zeros([10 10]);
flag(5,5)=1;
flag(5,9)=1;%Initialize Flag with 2 1's
temp=find(flag);%Find index of where the ones are, gives a 2x1 vector for both indecies
[I,J]=ind2sub(size(flag),temp);%Convert to columns and rows giving 2 2x1 vectors
flag((I-2):I,(J-2):J)=1;
flag((I-2):I,J:(J+2))=1;
flag(I:(I+2),(J-2):J)=1;
flag(I:(I+2),J:(J+2))=1;%Make flag values within 5x5 window 1, but it only does it for one of the flaged values?
My question is what is an efficient way to to this to ALL of the indecies in I and J? right now it only does it for the first one,
Thanks,
Chris

采纳的回答

Oleg Komarov
Oleg Komarov 2011-9-7
double(logical(conv2(flag,ones(5),'same')))

更多回答(1 个)

David Young
David Young 2011-9-7
You can use a loop, like this
% data
flag=zeros([10 10]);
flag(5,5)=1;
flag(5,9)=1;%Initialize Flag with 2 1's
%%find indices
temp=find(flag);%Find index of where the ones are, gives a 2x1 vector for both indecies
[I,J]=ind2sub(size(flag),temp);%Convert to columns and rows giving 2 2x1 vectors
% update array
for k = 1:length(I)
flag(I(k)-2:I(k)+2, J(k)-2:J(k)+2) = 1;
end
Alternatively, if you have the Image Processing Toolbox, you can just do
% data
flag=zeros([10 10]);
flag(5,5)=1;
flag(5,9)=1;%Initialize Flag with 2 1's
% dilate
flag = imdilate(flag, ones(5));
Note that the first method, with an explicit assignment, will grow the array to 11 columns in order to put ones in a 5x5 region round the (5,9) element. The second method will return an array the same size as the original.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by