Effacer les filtres
Effacer les filtres

Problem assigning multiple values simultaneously to a matrix

1 vue (au cours des 30 derniers jours)
Chris
Chris le 7 Sep 2011
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
  2 commentaires
Fangjun Jiang
Fangjun Jiang le 7 Sep 2011
use [I,J,V]=find(flag)
Fangjun Jiang
Fangjun Jiang le 7 Sep 2011
Pay attention that +2/-2 might exceed the size of the matrix.

Connectez-vous pour commenter.

Réponse acceptée

Oleg Komarov
Oleg Komarov le 7 Sep 2011
double(logical(conv2(flag,ones(5),'same')))

Plus de réponses (1)

David Young
David Young le 7 Sep 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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by