Undefined function or variable 't'.

4 次查看(过去 30 天)
jason law
jason law 2020-5-13
编辑: Stephen23 2020-5-13
I am trying on solving optimization problem but i gt the error
'Undefined function or variable 't'.
clear
clc
close all
%%
load('C:\Users\User\Desktop\fyp\defect_free(H).mat');
load('C:\Users\User\Desktop\fyp\f_column.mat');
load('C:\Users\User\Desktop\fyp\fi_column.mat');
load('C:\Users\User\Desktop\fyp\fr_column.mat');
fi=fi_column;
fr=fr_column;
f=f_column';
abs_H=abs(ifft(H));% getting magnitude of H from data in frequency domain
t1=[sort(rand(101,1))];
t2=[sort(rand(101,1))];
t=[t1 t2];
%%
problem = createOptimProblem('fmincon',...
'objective',@(t)obj(t1, t2,f,fr,fi),...
'x0',[sort(rand(101,1)),sort(rand(101,1))],'options',...
optimoptions(@fmincon,'Algorithm','sqp','Display','off'));
[x,fval] = fmincon(problem)
gs = GlobalSearch('Display','iter');
[x,fval] = run(gs,problem)
%%
function J=obj(t1, t2,f,fr,fi)
for x=1:101 % number of frequency
for y=1:101 %number of t
Fr(x,y)=cos(2*pi*f(x)*t(y)); %real number of F
Fi(x,y)=-i*sin(2*pi*f(x)*t(y)); % imaginary number of F
end
end
Fr_T=Fr';
Fi_T=Fi';
A=(Fr_T*Fr)+(Fi_T*Fi);
B=(Fr_T*fr)+(Fi_T*fi);
a=lsqminnorm(A,B) ; % solve tp get a set of a
J=sum((a-abs_H))^2 ;% to find the minimum of J from measured data
end
'
  1 个评论
Stephen23
Stephen23 2020-5-13
编辑:Stephen23 2020-5-13
There are a few issues related to t:
1- Your anonymous function has one input argument t, which is never used:
@(t)obj(t1, t2,f,fr,fi)
2- Inside the function obj you refer to a variable/function/class t which is undefined in the function.

请先登录,再进行评论。

回答(1 个)

Rik
Rik 2020-5-13
There are several problems with your code. The one causing the error is that you are using t in your inner loop in your obj function. It also looks like that nested loop could be an array operation, but without your data it is hard to confirm.
Speaking of data: you are poofing variables into existance with those load operations. You should load to a struct instead. That way you can show where each variable is coming from.
As a last point: don't use clear all. The usefulnes of close all is also questionable here, as you don't open any figures. If you want to clear your variables, use clear or clearvars. Outside of debugging you should be using functions to keep your workspace clean.

类别

Help CenterFile Exchange 中查找有关 Get Started with Optimization Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by