matlab,function,optimization,maximize , Matlab @fminunc objective function optimization

Matlab @fminunc objective function optimization


Tag: matlab,function,optimization,maximize

I am currently practicing a simple function optimization in Matlab and hope you could provide with little assistance / explanation on the following error:

function z=quadramin(param,data);
z=data.*(param(1).^2 - param(2).^3)+3;

function quadlik = quadramin_lik(param,data);
%pseudo/ad-hoc log-likelihood function
quadlik = quadramin(param,data)- 10;

[param_eq,exitflag,output,grad,hessian] = ... 
fminunc(@(param) quadramin_lik(param,data),param0)

Output after executing %script.m: Error using fminunc (line 333) User supplied objective function must return a scalar value.

ps: It looks paradoxical as the user-defined functions quadramin && quadramin_lik do return values.



Both your functions return a vector of values whereas fminunc requires that the function returns a scalar / single value. The error is pretty clear. The function fminunc is trying to find the best solution that minimizes a cost function, so what you need to supply is a cost function.

Therefore, perhaps try summing the results in each function before returning them.... but doing that doesn't guarantee a global minimum because fminunc assumes that your cost function is convex. However, judging from your comments as you are computing log likelihoods, then summing is what you should be doing any way!


Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

Saving images with more than 8 bits per pixel in matlab

I need to save a set of pre-processing images in matlab, resulting in grayscale images. The problem is the fact that these pre-processed images have pixel values higher than 255. If I save them with imwrite() as, for instance, .PNG files, does matlab normalize the values to be in [0,255]...

PercentOfSum(fld, condfld) SSRS Equivalent

Crystal Reports has a built-in function PercentOfSum(fld, condfld) (documentation here). How can I achieve the same functionality in SSRS?

Matlab - Multiply specific entries by a scalar in multidimensional matrix

I'm having problems multiplying specific values within my multidimensional matrix by a scalar. My matrix has the following dimension: size(comDatabe) = 5 10 3 397 10 The third dimension is an x-y-z coordinate frame. Something went wrong and now my y-axis is defined upside down for one subject (#8 out...

session value in javascript cannot be set

I am quite new to javascript, I wonder why my session value in javascript wont be set to 1 even I tried. When call this function again, the value of the session will change again. My javascript code as below. <script type="text/javascript"> function Confirm() { alert(<%=Session["Once"]%> != 1); var value...

How to skip a function

I am learning python and trying to make a little game. So my question is can you define a function but skip it and use it later. EX. def func() print"1,2,3,4" func() def func2() print "counting" func() func2() How would I skip func but still be able to print it...

Create string without repeating the same element jn the string (Matlab)

I have a string "FDFACCFFFBDCGGHBBCFGE" . Could anyone help me to generate a new string with the same order but no element inside repeated twice. Thanks ! The expected output should be like this : "FDACBGHE"...

JSLint won't recognize getElementById

JSLint gives errors with simple function, running on brackets with JSLint. Javascript: function soundSorry() { getElementById("player").play(); } Error codes: 2 Missing 'use strict' statement. getElementById("player").play(); 2 'getElementById' was used before it was defined. getElementById("player").play(); Any ideas?...

jQuery - Value in Function

My array: = "Thiago"; = "01/01/1990"; I want a function like this: function myFunc( array, fieldToCompare, valueToCompare ) { if( array.fieldToCompare == "Thiago" ) alert(true); } myFunc( myArray, name, "Thiago" ); is it possible?...

how to calculate probability for each class for predicate with knn without fitcknn?

my matlab version is 2012a. when I use fitcknn,has this error: Undefined function 'fitcknn' for input arguments of type 'cell'. how to calculate probability for each class for predicate with knn without fitcknn? after use this code, I want to calculate prob_estimates for each neighbors: knn =, trainlabel,'NumNeighbors',7); y...

what does ellipsis mean in a Matlab function's argument list?

What is the ellipsis for in this Matlab statement? frame = insertObjectAnnotation(frame, 'rectangle', ... bboxes, labels); ...I could not find in their online doc....

Decremented value called in the recursion in Haskell

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

Animate through multiple 2D Matlab plots

I have multiple 2D line plots in Matlab (they represent some wave moving through space). Each plot represents the wave at some time t. I want to animate through these plots (i.e. show the first plot for a fraction of a second, then show the next one, and the next,...

solve symbolic system of equations inside an array

sorry if it already has a answer..i tried other links but it didn't understand i have 2 1*63 array .landa and v. each of their members are syms. and each v member is a function of all landa members.i have already calculated v members and they are all symbolic equations...

How can I minimize this function in R?

I'm attempting to write a formula that will determine a value of a that minimizes the function output myfun (i.e. a-fptotal). MWE: c <- as.matrix(c(.25,.5,.25)) d <- as.matrix(c(10000,12500,15000)) e <- 700 f <- 1.1 tr <- .30 myfun <- function(a) { b <- max(a-e,0) df <- data.frame(u1=c(c*b*.40),u2=c(c*b*.60)) df$year <- 1:nrow(df)...

sum of Digits through Recursion

I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

Counting bytes received by posix read()

I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

Update input number variable onclick

I am trying to create a calculator style thing, where you put in how many years into a input, you hit submit and it gives you different results below without reloading the page. I have all the calculations working right now, but I just cant get the input number variable...

C++ need help figuring out word count in function. (Ex. Hello World = 2)

I'm figuring out the algorithm on this function and it keeps crashing at runtime, here's the code snippet: int wordCounter(char usStr[]) { int index= 0, punct= 0; while(usStr[index]!= '\0') //If it's not the end of the sentence if(usStr[index]== ' ') //If it finds a space index++; while(usStr[index]== '\0') //If it's...

matlab plots as movie with legend

i have a question regarding legend for movies. This is my code: fig = figure(); for i = 1: 70000 plot(signal1) hold on; plot([i,i],[-5,5]) plot(signal2,'r') hold off; title('\fontsize{14} my data'); legend('signal1','signal2'); axis tight; f(i) = getframe(fig); end The legend shows the same colors for the first two things I plot....

MATLAB Access Classreg

So, I want to be able to look at (read: copy) MATLAB's NonLinearModel method of printing the regression results to the screen such as this. Nonlinear regression model: y ~ (alpha1 - alpha2*t^0.5) Estimated Coefficients: Estimate SE tStat pValue alpha1 1.0253 0.0082253 124.66 4.8823e-24 alpha2 0.0061783 0.00073277 8.4314 4.4834e-07 Number...

Matlab — SVM — All Majority Class Predictions with Same Score and AUC = .50

I'm having a weird problem in training an SVM with an RBF kernel in Matlab. The issue is that, when doing a grid search, using 10-fold cross-validation, for the C and Sigma values I always get AUC values equal to approximately .50 (varying between .48 and .54 depending) -- I...

Plot multiple functions on one figure

I'm struggling to plot multiple functions on one figure. Here is the code that I have: syms t a; a=0.9514; F1=0.5*sqrt(3*t^2); F2=-0.28375*t^2+1.155*a*(t-a)+1; F3=1; E1=diff(F1,t); E2=diff(F2,t); E3=diff(F3,t); I want to plot E1, E2 and E3, each only within a certain range, to make a "composite" line. I've tried plotting with ezplot...

function wait to execute

In Matlab functions can be started at events,but occasionally, like with the resize function, the events are called in rapid order and the function is called many times in succession, which can cause weird behavior and lag. Is there a way to have it listen for the event but only...

Selecting and removing a html select option without selecting by index or ID, using vanilla JavaScript

I need to remove an option on a select box, and I've figured out a potential solution in the code below, but it doesn't feel particularly 'safe' (if another developer decided to add an option to the backend, the option will re-appear). Is there a better way of achieving this...

Create mask from bwtraceboundary in Matlab

I'm trying to create a mask (or similar result) in order to erase pieces of a binary image that are not attached to the object surrounded by the boundary. I saw this thread ( to do this from bwboundaries, but I'm having trouble making suitable changes to it. My goal...

SQL average age comparison function returns null

So, I'm working in MySQL, writing a function that averages the ages of women and men from a table and compares them, and returns which is greater. Dates are in the format of YYYY-MM-DD, and I'm using DATEDIFF(). The function appears to work correctly, but when I run the script,...

thicken an object of image to a curve in matlab

I have a labeled matrix containing two objects. How can I thicken an object to a curve? Actually I have the following image: and I want this: Each pixel of the resulting curve is the median of each column. But if you have another idea, it is acceptable, because I...

Replace paragraph in HTML with new paragraph using Javascript

I am attempting to replace a p in my HTML doc with a paragraph created in Javascript. Once the page loads, two will be replaced with t. var two = document.getElementById("two"); document.onload = function myFunction() { var p = document.createElement("p"); var t = document.createTextNode("I am the superior text"); p.appendChild(t); document.getElementById("p");...

How does ((a++,b)) work? [duplicate]

This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

Stuck on Structs(c++)

Okay so this is what Ive been asked to do "make a struct called Coordinate that contains the latitude and longitude of a point on the surface of the Earth. The struct should also store a label or name for the coordinate (e.g., “Calgary”). Both the latitude and longitude member...

How to normalise polynomial coefficients in a fraction?

I have the following code: syms z Gc=1.582*(1-0.3679*z^-1)/(1+.418*z^-1); Ghp=.3679*(z^-1)*(1+.718*z^-1)/((1-z^-1)*(1-.3679*z^-1)); T=(Gc*Ghp)/(1+Gc*Ghp); clipboard('copy', latex(simplifyFraction(T))); Which results in following for T: How can I normalise coefficients? I.e. I want the z2 in denominator and z in numerator to have the coefficient of 1. Is there any function in Matlab to do so?...

Can we add a statement in between MATLAB codes?

Is it possible to add statements in between the codes. For example: If I have a code like this, r(:,1) = a(:,1) - a(:,2); Then can I write it as, r(:,1) = a(:,1)("this is a constant") - a(:,2)("this is a variable"); ...

How to access variables in the properties block of a Matlab System Object?

I am working on a simple System Object in Matlab/Simulink. It looks like this : classdef realtime_header_detectorSO < matlab.System & matlab.system.mixin.Propagates % correlateHeader % % This template includes the minimum set of functions required % to define a System object with discrete state. properties Header %nrOfBitsInPreviousStep=0; s=100; d=zeros(1,s); end properties...

Plotting random signal on circle

I have some random signal (for example sin signal) with the time scale. t=0:0.1:2*pi y=sin(t) plot(t,y) Now I want to draw this signal on this circle. So the time vector actually becomes an envelope of the circle. Envelope of the circle represents "y = 0" in cartesian coordinate system. Here...

How to switch Matlab plot tick labels to scientific form?

I have a semilogarithmic plot which works so far with semilogx. Now I would like to change the tick labels. Now it says 10^8 10^9 ... 10^13, but I would like to see 1e8, 1e9, ... 1e13 on the x-axis. How can I change that? Cheers Manuel...

Is it possible to use $(this) in a function called from another function?

Sorry for the question title, I know it's not very well worded, but I couldn't really explain what I'm asking in a summary. I have a JQuery function tied to the click event of an element. For reasons that may well be flawed (other than making more sense to me...

How to force my output data in a inputdlg on Matlab be a double?

I'm currently using a MATLAB to work and I need some help: I need to convert my output data (variable: units) be a double instead of a cell because I must perform a sum: units = inputdlg(question,title); sum = units + i; I've tried this code also but didn't solve...

xcorr function with impulse response

I'm trying to design a Wiener filter in Matlab for a deconvolution problem but I'm having a lot of problems. I have a gaussian white noise process with a variance of 1.2 and a impulse response which has length two. Its values are g(0) = 5 and g(1) = 4....

Calling function and passing arguments multiple times

I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

Can't understand this Javascript function (function overloading)

I'm reading Secrets of Javascript Ninja and came across an example that I cannot fully understand. This same example was cited by some other user here before, but their doubts are different than mine. Here is the example: function addMethod(object, name, fn) { var old = object[name]; object[name] = function(){...

Call known function (with parameters) in class whose name is defined by string variable

I have a bunch of classes of various names and each has a performLogic function that accepts a number of preset parameters (always the same): public final class DoSomeAction extends SetupAction { public void performLogic(param1, param2... I want a way where I can call it like this: String actionName =...

Giving a string variable as a filename in matlab

I am using the below mentioned code to get the file names of images according to their id's from images_1 text file as strings and use them to read the images from their directory image_count=1; for image_count=1:6 file=fopen('D:\Academics\New folder\CUB_200_2011\images_1.txt','r'); C = textscan(file, '%s'); original_image=imread('D:\Academics\New folder\CUB_200_2011\images\%s','C{1}{2*(image_count)}'); imshow(original_image) end I am able...

Why black surf from this Matlab command?

Code tfr = abs ( tfr ); [row_size, column_size] = size(tfr); tfr = tfr(1:round(row_size/2), 1:row_size); surf(tfr); view(2); I get in R2014b of OSX 10.10.3 Yosemite but rotating around shows that the cells should not be black Why is the output black? I wonder if this is a hardware problem or...

Interpolation inside a matrix. Matlab

I have a matrix looks like: 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 0 4 0 0 0 0 0 3 0 0 6 0 0 4...

Operating a C++ class from Matlab without mex [closed]

Is there an alternative way to call a C++ class using MATLAB, and operate its methods on MATLAB variables?

Connecting two binary objects in matlab

I have a binary matrix containing several binary objects and I want to bridge between them. Actually I have the following picture: And the result has to be like this: Is there any function or a shortcut way, other than loops, for this problem?...

MySQL function with parameters syntax error

I'm trying to convert this query to a MySQL function SET @v1 := ( SELECT count(id) as count FROM article_category where (title like "About Usd") or (title like "About Usd-%" and title regexp '[0-9]$') ); INSERT INTO `article_category` (`title`,`meta_data`,`meta_description`) VALUES ( IF(@v1 <= 0, "About Usd", CONCAT("About Usd","-",@v1) ), "ddddD",...

two dimensional unique values in Matlab

I have two vectors, one of them stores the width dimension of a set of images and another one the height of these set of images. I want to use these values as two dimensional vectors [width height] and store them in a matrix. The first line, for instance, keeps...

Reading all the files in sequence in MATLAB

I am trying to read all the images in the folder in MATLAB using this code flst=dir(str_Expfold); But it shows me output like this. which is not the sequence as i want. Can anyone please tell me how can i read all of them in sequence? for giving downmark, please...