Azzera filtri
Azzera filtri

Problem assigning multiple values simultaneously to a matrix

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Oleg Komarov
Oleg Komarov il 7 Set 2011
double(logical(conv2(flag,ones(5),'same')))

Più risposte (1)

David Young
David Young il 7 Set 2011
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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by