array index

조회 수: 3 (최근 30일)
Rakshmy  C S
Rakshmy C S 2011년 12월 5일
Hi, I have declared the size of array as 4*4.When i run the third for loop the size of array becomes 49*49.Dont know why this happens in that loop?
pat1='11';
arr=zeros(4,4);
len=length(pat1);
for i=1:4
for j=1:4
arr(i,j)=l+2;
end
end
for j=1:4
arr(1,j)=1;
end
for i=1:len-1
arr(pat1(i),pat1(i+1))=l-i;
end
for i=1:4
arr(i,1)=l+1;
end
[EDITED, Jan Simon, Code formatted]
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 12월 5일
http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup

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

채택된 답변

the cyclist
the cyclist 2011년 12월 5일
Because "pat1" is a character array, you are accessing the numerical equivalent of the character '1', which is 49. MATLAB is implicitly using "double('1')" to convert that character to a numeric.
Not sure why you defined pat1 that way, but you could use the following in your third loop:
arr(str2num(pat1(i)),str2num(pat1(i+1)))=l-i;
(If that is indeed what you intend.)
  댓글 수: 3
the cyclist
the cyclist 2011년 12월 5일
It would be helpful if you were to "Accept" an answer, signaling to future users that the Question was answered.
Walter Roberson
Walter Roberson 2011년 12월 5일
But what if the pattern did not happen to correspond to numeric characters?
If you are *sure* that pat1 will contain only numeric characters, then the str2num() calls that the cyclist shows can be replaced:
arr(pat1(i)-'0', pat1(i+1)-'0') = 1-i;

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 12월 5일
49 is the numeric equivalent of the character '1' . You are trying to index your array "arr" at the character pat1(i)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by