Nested loop problem !

조회 수: 2 (최근 30일)
Susan
Susan 2011년 7월 26일
Hey every1.. I am working on arrays and I am finding it quite confusing and slowly getting it.. I want to replace the content of a double array with another double array and I belive since is double I should use a nested loop but I am not sure how it works?? I tried several of ways which is below but the content is not being replaced.. I keep checking it from the matlab work space .. My code is below.. the size is 2x100 and in matlab workspace is two rows.. with my code instead of replacing the content it adds extra row to array b?? I want to start the replace from a(3,1) with b(1,1). a(4,1) with b(2,1) etc then when it finishes this row the second row etc
a(x;y)
b(s,f)
d = 2;
for i=3,j=1:100
a(i,j) = b(i -d,j);
i = i+1;
j = j+1
end
Thanks in advance !!
  댓글 수: 1
Nathan Greco
Nathan Greco 2011년 7월 27일
Note that if your arrays are size 2x100, then you should be indexing them as "a(1,3) with b(1,1). a(1,4) with b(1,2)". (How can you reach a(4,1) if there are only two rows in a? (Note that indexing goes a(row,column))

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

채택된 답변

Nathan Greco
Nathan Greco 2011년 7월 26일
Will this do what you are looking for:
EDIT:
a(:,3:end) = b(:,1:end-2);
OR, if you really wanted a for loop:
d = 2;
for i=1:100-d
a(:,i+2) = b(:,i);
end
-Nathan
  댓글 수: 7
Nathan Greco
Nathan Greco 2011년 7월 27일
Based on "test" data that I am using that just use the dimensions you provided (2x100), my method seems to work. I used a = ones(2,100); and b = rand(2,100);
The result from a(:,3:end) = b(:,1:end-2); (this line alone, no for loop involved) turns a into a 2x100 (same size) array, with a(1:2,1:2) remaining ones, and the rest of a having been replaced with b.
Susan
Susan 2011년 7월 27일
Yeah, It worked perfectly fine.. was looking at the columns but read your comment that it starts with rows.. Thanks alot for your help.. Now I can carry on and learning more about the loops and arrays :)

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2011년 7월 27일
eg:
a = randi(15,4,10) % array 4x10
b = randi(20,2,10) %array 2x10
a(3:end,:)=b
  댓글 수: 8
Susan
Susan 2011년 7월 27일
Yeah thats exactly what I would like to do!!
Nathan Greco
Nathan Greco 2011년 7월 27일
And, sorry for mixing up terminology, the "rows" should actually be "columns".

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

카테고리

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