필터 지우기
필터 지우기

Problem assigning multiple values simultaneously to a matrix

조회 수: 1 (최근 30일)
Chris
Chris 2011년 9월 7일
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
Fangjun Jiang
Fangjun Jiang 2011년 9월 7일
use [I,J,V]=find(flag)
Fangjun Jiang
Fangjun Jiang 2011년 9월 7일
Pay attention that +2/-2 might exceed the size of the matrix.

댓글을 달려면 로그인하십시오.

채택된 답변

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