for loop mixing the results with the previous loops
    조회 수: 12 (최근 30일)
  
       이전 댓글 표시
    
Hi
I am using the following loop for evey 10 row of my array (20 row or more* 2 column). then, I want to save the results (Z or res).
converted = table2array(imported);
n=2;
for ind = 1:n
    tmp = converted((n-1)*10+1:n*10,:);
    X = tmp
    X = [true;diff(converted(:,1))~=0];
    Y = diff(find([X;true]));
    V = accumarray(cumsum(X),~converted(:,2));
    Z = [Y,V]
end
res(:,:,ind)= Z
The problem is the code also runs for row 11 (should be first 10 ) then for the next 10 row starts to run from row 12 (which should be 11-20).
This means mixing first 10 rows result with the second batch of 10 rows.
correct sample for  10 rows:
>> M = [0,0;0,1;1,1;1,0;1,1;1,0;0,1;1,1;0,1;0,1]
M =
   0   0
   0   1
   1   1
   1   0
   1   1
   1   0
   0   1
   1   1
   0   1
   0   1
>> X = [true;diff(M(:,1))~=0];
>> Y = diff(find([X;true]));
>> V = accumarray(cumsum(X),~M(:,2));
>> Z = [Y,V]
Z =
   2   1
   4   2
   1   0
   1   0
   2   0
댓글 수: 0
답변 (1개)
  Dheeraj Singh
    
 2019년 12월 19일
        The issue is that for loop variable ind is outside the for loop
You can try the following code:
converted = table2array(imported);
n=2;
for ind = 1:n
    (ind-1)*10+1
    ind*10
    tmp = converted((ind-1)*10+1:ind*10,:)
    X = tmp
    X = [true;diff(converted(:,1))~=0];
    Y = diff(find([X;true]));
    V = accumarray(cumsum(X),~converted(:,2));
    Z = [Y,V]
    res(:,:,ind)= Z;
end
댓글 수: 0
참고 항목
카테고리
				Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

