How to define a matrix which changes its size in every iteration of loop?
22 次查看(过去 30 天)
显示 更早的评论
T = 50; %total iteration
x = randn(T,1); %input
pw =[0,0,0,0,0,1,-0.3,0.2]; % primary path TF
d = filter(pw, 1, x); % desiresd input
mu = 0.1; %step size
g = 1e-12; %gamma
%p = 2; %projection order
N = 8; %no of taps
Pmax = 4;
w = zeros(N,1); % weights of controller
y = zeros(1,T); % output of controller
%Xi = zeros(p,N); %input matrix
e_cont = zeros(T,1); %residual noise
p = zeros(T,1);
p(1)=Pmax;
for i=1:T
Xi(2:p(i),:) = Xi(1:p(i),:);
Xi(1,:) = [ x(i:-1:max(i-N+1,1)).',zeros(1,max(N-i,0)) ];
di = transpose([ d(i:-1:max(i-p(i)+1,1)).',zeros(1,max(p(i)-i,0)) ]);
Yi = Xi*w;
err= di-Yi;
sqe = err.^2;
UT = (mu*p(i)+2)*var/(2-mu);
LT = (mu*(p(i)-1)+2)*var/(2-mu);
if sqe(p(i)) > UT
p(i+1) = min(p(i)+1,Pmax);
elseif sqe(p(i))<= LT
p(i+1) = max(p(i)-1,1);
else
p(i+1) = p(i);
end
w = w + mu*Xi'*inv(g*eye(p(i))+Xi*Xi')*(di-Yi);
e_cont(i)= err(p(i));
end;
4 个评论
Stephen23
2021-2-23
编辑:Stephen23
2021-2-23
Original question by zahid fazal retrieved from Google Cache:
How to define a matrix which changes its size in every iteration of loop?
T = 50; %total iteration
x = randn(T,1); %input
pw =[0,0,0,0,0,1,-0.3,0.2]; % primary path TF
d = filter(pw, 1, x); % desiresd input
mu = 0.1; %step size
g = 1e-12; %gamma
%p = 2; %projection order
N = 8; %no of taps
Pmax = 4;
w = zeros(N,1); % weights of controller
y = zeros(1,T); % output of controller
%Xi = zeros(p,N); %input matrix
e_cont = zeros(T,1); %residual noise
p = zeros(T,1);
p(1)=Pmax;
for i=1:T
Xi(2:p(i),:) = Xi(1:p(i),:);
Xi(1,:) = [ x(i:-1:max(i-N+1,1)).',zeros(1,max(N-i,0)) ];
di = transpose([ d(i:-1:max(i-p(i)+1,1)).',zeros(1,max(p(i)-i,0)) ]);
Yi = Xi*w;
err= di-Yi;
sqe = err.^2;
UT = (mu*p(i)+2)*var/(2-mu);
LT = (mu*(p(i)-1)+2)*var/(2-mu);
if sqe(p(i)) > UT
p(i+1) = min(p(i)+1,Pmax);
elseif sqe(p(i))<= LT
p(i+1) = max(p(i)-1,1);
else
p(i+1) = p(i);
end
w = w + mu*Xi'*inv(g*eye(p(i))+Xi*Xi')*(di-Yi);
e_cont(i)= err(p(i));
end;
采纳的回答
Walter Roberson
2021-2-20
It is legal to change the size of a matrix inside a loop, including being legal to let it grow one element at a time every iteration. However, it is more efficient if you can create the matrix at full size ahead of time. Sometimes much more efficient.
The problem with your code is that you do not initialize the variable Xi but you have
Xi(2:p(i),:) = Xi(1:p(i),:);
That requires that rows 1 to Pmax and all columns of Xi are initialized before the statement is executed -- but Xi is undefined here.
Also, the right hand side has p(i)-1+1 = p(i) rows, but the left hand side has p(i)-2+1 = p(i)-1 rows . This is a mismatch: you would be trying to store 4 rows of data into a location that only holds three rows.
3 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Image Segmentation and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!