# Your objective function is not a scalar

Dear all,
I am running my code and saw an error as below. I am a newbie in CVX and please help me to solve this problem. Thank you so much

``````clc; clear; close all;
P_0 = 580.65; P_1 = 790.6715; P_p = 7.258125e-3;
A = 7.5e-5; B = 9.3655e-5; D = sqrt(B);
% Length of each hop in the subset UAV_U1
d = [13.0306652051091;29.4783910754631;37.3021366802836;5.82299654643107;76.4042125718663];
delay_U1 = [8;5;6;5;5]; % Delay tolerance of each user in U1

init_x = ones(length(delay_U1),1); % Initial value of x
step = 0.7; % step size value
t_p = 0.1; % packet transmission time

err = 1.0;
lamda = 1e-4; % Error threshold
max_iter = 1000;% Total number of iteration
iter = 1; % Number of iteration
all_error = [];
all_y = [];
lb = ones(length(delay_U1),1);% Lower bound of the constraint
ub = 60*ones(length(delay_U1),1);% Upper bound of the constraint

% Call CVX to solve the LP problem
%g_x = zeros(length(delay_U1),1);
while (err > lamda && iter <= max_iter)
[y, gradient] = GD_func(init_x); % Calculate the y and gradient value at init_x
all_y = [all_y, y];
cvx_begin
g_x = 0;
variable x(length(delay_U1),1)
g_x = g_x + y + (vec(x)-vec(init_x))*gradient; % Approximation function using Taylor series at first order
whos
minimize (g_x)
%init_x = x;
sub = cvx(zeros(length(delay_U1),1));
for i=1:length(delay_U1)
if i==1
sub(1)= d(1)*inv_pos(x(1)) + t_p;
%sub(1) <=  delay_U1(1);
else
sub(i) =  sub(i-1) + d(i)*inv_pos(x(i)) + t_p;
%sub(i) <= delay_U1(i);
end
end
subject to
vec(sub) <= vec(delay_U1);
lb <= vec(x);
vec(x) <= ub;
cvx_end
new_x = x;
new_err = abs(new_y - y)^2;
all_error = [all_error, new_err];

err = new_err;
init_x = new_x;
end
function [ y, grad ] = GD_func( x )
%FUNC Summary of this function goes here
%   Detailed explanation goes here
P_0 = 580.65; P_1 = 790.6715; P_p = 7.258125e-3;
B = 7.5e-5; C = 9.3655e-5; D = sqrt(C); delay_U1 = [8,5,6,5,5];
d = [13.0306652051091;29.4783910754631;37.3021366802836;5.82299654643107;76.4042125718663];

for i=1:5
y = y + P_0*(x(i)^(-1)+B*x(i))+P_1*(sqrt(x(i)^(-4)+D^2)-D)^0.5 + P_p*x(i)^2;
end
end
``````

After running my code, I got this error “Your objective function is not a scalar. Error in Test_CVX_Our_Problem (line 48)
cvx_end”. What am I doing wrong?

What is G`D_func` ? SO what are y and gradiient as its output? And does ```
vec(x)-vec(init_x))*gradient; evaluate to a scalar? I don;t see how it would.

Hint: if ypu use MATLAB variables instead of CVX variables, the expressions must be conformal, and in the case of an objective function, must evaluate to a (real) scalar. As the error message says, your does not.

1 Like

Dear Mark,

Thank you so much for your useful recommendations. I think I solved my problems.

Have a nice weekend.