How to tell a loop to do an iteration when a new row is added to the matrix?

조회 수: 1 (최근 30일)
Hi all. I have the following loop:
x1=[6;6;5;10;7;6;5;3;8;8;5;8;5;4;2;7;4;5;7;1;5;4;7;4;8]; %variable 1
x2=[8;7;7;9;9;6;8;7;8;6;9;8;8;9;9;5;8;10;7;5;6;3;9;5;9]; %variable 2
x3=[3;3;1;8;7;3;6;3;9;5;5;2;7;10;4;8;8;9;3;2;7;1;6;2;5]; %variable 3
x4=[5;4;4;4;6;9;7;6;3;3;4;3;5;2;10;6;2;3;7;7;7;2;6;4;7]; %variable 4
x5=[19;9;16;4;9;17;6;16;8;13;17;5;8;16;14;15;16;11;12;17;20;15;9;12;18]; %variable 5
n=numel(x1);
c=[x1,x2,x3,x4,x5];%used for covariance matrix
k=size(c,2);nk=n-k;
n1=10
for z=1:size(x1,1)
c1=c(z:9+z,:);
mean1=mean(c1,1);S_c=cov(c1);is_c=inv(S_c);diff_c=[mean1'-Goal];T2_c(z)=n1*[(diff_c'*is_c)* diff_c];
plot(T2_c,'-o')
line('XData', [0 25], 'YData', [16.2653 16.2653], 'LineStyle', '-', 'LineWidth', 2, 'Color','r')
end
I basically want the for loop to run every time a new row of data is added to the matrix c( a new value is added to x1, x2,x3,x4,x5).
Also is it possible to have matlab to pull out every 2nd and 3rd number of a matrix. for example, if [1,2,3,4,5,6,7,8,9,10]. i want to pull out 2,4,6,8 etc and 3,6,9,etc.
Thank you for your help!

채택된 답변

per isakson
per isakson 2014년 11월 17일
편집: per isakson 2014년 11월 17일
"[1,2,3,4,5,6,7,8,9,10]. [I] want to pull out 2,4,6,8 etc and 3,6,9,etc." that's easy:
>> vec = [1,2,3,4,5,6,7,8,9,10];
>> vec(2:2:end)
ans =
2 4 6 8 10
>> vec(3:3:end)
ans =
3 6 9
>>
or
>> for jj = 2:10, vec(jj:jj:end), end
ans =
2 4 6 8 10
ans =
3 6 9
ans =
4 8
etc.
>>
if 10 shall not be included replace &nbsp :end &nbsp by &nbsp :end-1
&nbsp
"run every time a new row of data is added to the matrix" &nbsp Yes, it's possible. One way is to use
  • OOP and
  • the property attribute, SetObservable &nbsp If true, and it is a handle class property, then you can create listeners for access to this property. The listeners are called whenever property values are modified. See Property-Set and Query Events
  댓글 수: 3
per isakson
per isakson 2014년 11월 19일
편집: per isakson 2014년 11월 19일
I'm missing something
>> vec(1:3:end)
ans =
1 4 7 10
already returns 10. To make sure 10, the last element, is always included
for jj = 1 : 10
vec( unique( [ 1:jj:length(vec), length(vec)] ) )
end
which returns
ans =
1 2 3 4 5 6 7 8 9 10
ans =
1 3 5 7 9 10
ans =
1 4 7 10
ans =
1 5 9 10
etc.
unique ensures that a single 10 is returned. Here is a bit of smell of Matlab. Better
for jj = 1 : 10
out = vec( 1:jj:length(vec) );
if out(end)~=10
out(end+1) = 10;
end
disp( out )
end
next step is to replace the magic number 10 by a variable with a good name.

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

추가 답변 (0개)

카테고리

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