Weird error while using constant properties in class - matlab

I am trying to save functions as variables inside a class so I can reach them in an ordered manner. However, whenever I try to pull any constant from the following class, I get the following error.
%FORMULAS Summary of this class goes here
% Detailed explanation goes here
properties (Constant)
%F.heatCapacityOfLiquid
t = #(z) z *2
end
properties (Constant)
enthalpyChange = #(constants, temperatureIn, temperatureOut)integral(#(temperature)(#(constants, temperature)...
constants(1)...
+ temperature * constants(2)...
+ temperature.^2 * constants(3)...
+ temperature.^3 * constants(4)), 0,10);
heatCapacityOfLiquid = #(constants, temperature) constants(1)...
+ temperature * constants(2)...
+ temperature.^2 * constants(3)...
+ temperature.^3 * constants(4);
end
end
ERROR
>> F.t
Invalid default value for property 'enthalpyChange' in class 'F':
Error: Invalid use of operator.

Related

ABAP drag and drop object on ALV GRID

I discover the Drag AND Drop object on my alv grid, but when I search documentation it's hard to understand the process flow ,
I have a lot of questions :
I want to block the possibility to drag and drog on some columns.
And I want that the sign that not allowed appear.
I want that when I select more than one line, On the drop place display the focus on more than one cell.
This is my code :
In My Class : In the Definition
on_drag FOR EVENT ondrag OF cl_gui_alv_grid
IMPORTING e_column e_row es_row_no e_dragdropobj,
on_drop FOR EVENT ondrop OF cl_gui_alv_grid
IMPORTING e_column e_row es_row_no e_dragdropobj,
In the Implementation:
METHOD on_drag.
DATA: lr_objct TYPE REF TO lcl_dragdropobj.
CREATE OBJECT lr_objct.
gr_alvpl->get_selected_cells( IMPORTING et_cell = lr_objct->lt_cells ).
e_dragdropobj->object = lr_objct.
ENDMETHOD. "on_drag
METHOD on_drop.
DATA: lv_lines TYPE i,
lv_tolin TYPE i,
lv_icone TYPE icon,
ls_cells TYPE lvc_s_cell,
ls_colmn TYPE lvc_s_col,
ls_trows TYPE lvc_s_row,
ls_tbalv TYPE zscad_planification,
lv_value TYPE string,
lr_objct TYPE REF TO lcl_dragdropobj.
FIELD-SYMBOLS: <struc> TYPE zscad_planification,
<value> TYPE ANY.
PERFORM verif_before_dad.
lr_objct ?= e_dragdropobj->object.
DESCRIBE TABLE lr_objct->lt_cells LINES lv_lines.
lv_tolin = e_row + lv_lines.
*
* DATA: lt_field TYPE TABLE OF sval,
* ls_field TYPE sval.
*
* ls_field-fieldname = 'comment'.
* ls_field-fieldtext = 'Vous pouvez saisir un message'.
* APPEND ls_field TO lt_field.
* CALL FUNCTION 'POPUP_GET_VALUES'
* EXPORTING
** NO_VALUE_CHECK = ' '
* popup_title = 'Confirmation'
** START_COLUMN = '5'
** START_ROW = '5'
** IMPORTING
** RETURNCODE =
* tables
* fields = lt_field
** EXCEPTIONS
** ERROR_IN_FIELDS = 1
** OTHERS = 2
* .
* IF sy-subrc <> 0.
** MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
** WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
* ENDIF.
LOOP AT lr_objct->lt_cells INTO ls_cells.
CLEAR: ls_colmn, ls_trows.
ls_colmn = ls_cells-col_id.
ls_trows = ls_cells-row_id.
READ TABLE gt_tbalv ASSIGNING <struc> INDEX ls_trows-index.
IF sy-subrc EQ 0.
CONCATENATE '<struc>-' ls_colmn-fieldname INTO lv_value.
ASSIGN (lv_value) TO <value>.
lv_icone = <value>.
CLEAR: <value>.
ENDIF.
ENDLOOP.
* Fill the new Day
LOOP AT lr_objct->lt_cells INTO ls_cells.
CLEAR: ls_colmn, ls_trows.
ls_colmn = e_column.
* ls_colmn = ls_cells-col_id.
ls_trows = ls_cells-row_id.
READ TABLE gt_tbalv ASSIGNING <struc> INDEX ls_trows-index.
IF sy-subrc EQ 0.
CONCATENATE '<struc>-' ls_colmn-fieldname INTO lv_value.
ASSIGN (lv_value) TO <value>.
<value> = lv_icone.
ENDIF.
ENDLOOP.
gr_alvpl->refresh_table_display( ).
ENDMETHOD. "on_drop
METHOD on_date_selected.
gv_datax = date_begin.
PERFORM destroy_all_object.
* PERFORM refresh_alv.
ENDMETHOD.
And when I build my ALV, I launch this routine :
FORM alv_dragdrop.
DATA: lv_effct TYPE i,
lv_hndla TYPE i,
ls_dragd TYPE lvc_s_dd01.
* Define a behaviour for drag and drop on ALV objects and get its handle.
* Define a drag & Drop behaviour for the whole grid
CREATE OBJECT gr_dragd.
lv_effct = cl_dragdrop=>move + cl_dragdrop=>copy.
CALL METHOD gr_dragd->add
EXPORTING
flavor = 'Line'
dragsrc = 'X'
droptarget = 'X'
effect = lv_effct.
CALL METHOD gr_dragd->get_handle
IMPORTING
handle = lv_hndla.
* Provide handle to alv control using the layout-structure
ls_dragd-row_ddid = lv_hndla.
gs_layou-s_dragdrop = ls_dragd.
ENDFORM. " ALV_DRAGDROP
Thanks. Regards,
I think that it s not possible

Matlab: replace specific argument that appears more than once

let's say I have s=g(1,2,0)+g(1,3,0)+u(1,3)+g(1,1,0) where g, u are functions; I want to replace all 3rd arguments of g to something I choose without going through my script and doing it manually.
x = ... % assign some value beforehand
s = g(1,2,x) + g(1,3,x) + u(1,3) + g(1,1,x)
What follows is an ugly hack and I don't recommend using it:
g = #(a,b,c) g(a,b,0)
This redefines g function in a way that executing after that:
s = g(1,2,5) + g(1,3,3) + u(1,3) + g(1,1,2)
actually executes:
s = g(1,2,0) + g(1,3,0) + u(1,3) + g(1,1,0)

Finding all solutions to a non-linear equation system with MuPAD

My question is if there is a good way to use MuPAD functions in a Matlab script. The background is that I have a problem where I need to find all solutions to a set of non-linear equations. The previous solution was to use solve in Matlab, which works for some of my simulations (i.e., some of the sets of input T) but not always. So instead I'm using MuPAD in the following way:
function ut1 = testMupadSolver(T)
% # Input T should be a vector of 15 elements
mupadCommand = ['numeric::polysysroots({' eq1(T) ' = 0,' ...
eq2(T) '= 0},[u, v])'];
allSolutions = evalin(symengine, mupadCommand);
ut1 = allSolutions;
end
function strEq = eq1(T)
sT = #(x) ['(' num2str(T(x)) ')'];
strEq = [ '-' sT(13) '*u^4 + (4*' sT(15) '-2*' sT(10) '-' sT(11) '*v)*u^3 + (3*' ...
sT(13) '-3*' sT(6) '+v*(3*' sT(14) '-2*' sT(7) ')-' sT(8) '*v^2)*u^2 + (2*' ...
sT(10) '-4*' sT(1) '+v*(2*' sT(11) '-3*' sT(2) ')+v^2*(2*' sT(12) ' - 2*' ...
sT(3) ')-' sT(4) '*v^3)*u + v*(' sT(7) '+' sT(8) '*v+' sT(9) '*v^2)+' sT(6)];
end
function strEq = eq2(T)
sT = #(x) ['(' num2str(T(x)) ')'];
strEq = ['(' sT(14) '-' sT(13) '*v)*u^3 + u^2*' '(' sT(11) '+(2*' sT(12) '-2*' sT(10) ...
')*v-' sT(11) '*v^2) + u*(' sT(7) '+v*(2*' sT(8) '-3*' sT(6) ')+v^2*(3*' sT(9) ...
'-2*' sT(7) ') - ' sT(8) '*v^3) + v*(2*' sT(3) '-4*' sT(1) '+v*(3*' sT(4) ...
'-3*' sT(2) ')+v^2*(4*' sT(5) ' - 2*' sT(3) ')-' sT(4) '*v^3)+' sT(2)];
end
I have two queries:
1) In order to use MuPAD I need to rewrite my two equations for the equation-system as strings, as you can see above. Is there a better way to do this, preferably without the string step?
2) And regarding the format output; when
T = [0 0 0 0 0 0 0 0 0 0 1 0 1 0 1];
the output is:
testMupadSolver(T)
ans =
matrix([[u], [v]]) in {matrix([[4.4780323328249527319374854327354], [0.21316518769990291263811232040432]]), matrix([[- 0.31088044854742790561428736573347 - 0.67937835289645431373983117422178*i], [1.1103383836576028262792542770062 + 0.39498445715599777249947213893789*i]]), matrix([[- 0.31088044854742790561428736573347 + 0.67937835289645431373983117422178*i], [1.1103383836576028262792542770062 - 0.39498445715599777249947213893789*i]]), matrix([[0.47897094942962218512261248590261], [-1.26776233072168360314707025141]]), matrix([[-0.83524238515971910583152318717102], [-0.66607962429342496204955062300669]])} union solvelib::VectorImageSet(matrix([[0], [z]]), z, C_)
Can MuPAD give the solutions as a set of vectors or similarly? In order to use the answer above I need to sort out the solutions from that string-set of solutions. Is there a clever way to do this? My solution so far is to find the signs I know will be present in the solution, such as '([[' and pick the numbers following, which is really ugly, and if the solution for some reason looks a little bit different than the cases I've covered it doesn't work.
EDIT
When I'm using the solution suggested in the answer below by #horchler, I get the same solution as with my previous implementation. But for some cases (not all) it takes much longer time. Eg. for the T below the solution suggested below takes more than a minute whilst using evalin (my previous implementation) takes one second.
T = [2.4336 1.4309 0.5471 0.0934 9.5838 -0.1013 -0.2573 2.4830 ...
36.5464 0.4898 -0.5383 61.5723 1.7637 36.0816 11.8262]
The new function:
function ut1 = testMupadSolver(T)
% # Input T should be a vector of 15 elements
allSolutions = feval(symengine,'numeric::polysysroots', ...
[eq1(T),eq2(T)],'[u,v]');
end
function eq = eq1(T)
syms u v
eq = -T(13)*u^4 + (4*T(15) - 2*T(10) - T(11)*v)*u^3 + (3*T(13) - 3*T(6) ...
+ v*(3*T(14) -2*T(7)) - T(8)*v^2)*u^2 + (2*T(10) - 4*T(1) + v*(2*T(11) ...
- 3*T(2)) + v^2*(2*T(12) - 2*T(3)) - T(4)*v^3)*u + v*(T(7) + T(8)*v ...
+ T(9)*v^2) + T(6);
end
function eq = eq2(T)
syms u v
eq = (T(14) - T(13)*v)*u^3 + u^2*(T(11) + (2*T(12) - 2*T(10))*v ...
- T(11)*v^2) + u*(T(7) + v*(2*T(8) - 3*T(6) ) + v^2*(3*T(9) - 2*T(7)) ...
- T(8)*v^3) + v*(2*T(3) - 4*T(1) + v*(3*T(4) - 3*T(2)) + v^2*(4*T(5) ...
- 2*T(3)) - T(4)*v^3) + T(2);
end
Is there a good reason to why it takes so much longer time?
Firstly, Matlab communicates with MuPAD via string commands so ultimately there is no way of getting around the use of strings. And because it's the native format, if you're passing large amounts of data into MuPAD, the best approach will be to convert everything to strings fast and efficiently (sprintf is usually best). However, in your case, I think that you can use feval instead of evalin which allows you to pass in regular Matlab datatypes (under the hood sym/feval does the string conversion and calls evalin). This method is discussed in this MathWorks article. The following code could be used:
T = [0 0 0 0 0 0 0 0 0 0 1 0 1 0 1];
syms u v;
eq1 = -T(13)*u^4 + (4*T(15) - 2*T(10) - T(11)*v)*u^3 + (3*T(13) - 3*T(6) ...
+ v*(3*T(14) -2*T(7)) - T(8)*v^2)*u^2 + (2*T(10) - 4*T(1) + v*(2*T(11) ...
- 3*T(2)) + v^2*(2*T(12) - 2*T(3)) - T(4)*v^3)*u + v*(T(7) + T(8)*v ...
+ T(9)*v^2) + T(6);
eq2 = (T(14) - T(13)*v)*u^3 + u^2*(T(11) + (2*T(12) - 2*T(10))*v ...
- T(11)*v^2) + u*(T(7) + v*(2*T(8) - 3*T(6) ) + v^2*(3*T(9) - 2*T(7)) ...
- T(8)*v^3) + v*(2*T(3) - 4*T(1) + v*(3*T(4) - 3*T(2)) + v^2*(4*T(5) ...
- 2*T(3)) - T(4)*v^3) + T(2);
allSolutions = feval(symengine, 'numeric::polysysroots',[eq1,eq2],'[u,v]');
The last argument still needed to be a string (or omitted) and adding ==0 to the equations also doesn't work, but the zero is implicit anyways.
For the second question, the result returned by numeric::polysysroots is very inconvenient and not easy to work with. It's a set (DOM_SET) of matrices. I tried using coerce to convert the result to something else to no avail. I think you best bet it to convert the output to a string (using char) and parse the result. I do this for simpler output formats. I'm not sure if it will be helpful, but feel free to look at my sym2float which just handles symbolic matrices (the 'matrix([[ ... ]])' part go your output) using a few optimizations.
A last thing. Is there a reason your helper function includes superfluous parentheses? This seems sufficient
sT = #(x)num2str(T(x),17);
or
sT = #(x)sprintf('%.17g',T(x));
Note that num2str only converts to four decimal places by default. int2str (or %d should be used if T(x) is always an integer).

Matlab erasing my values

I'm writing a OOP on Matlab, a naive bayes for separating email. Like this
classdef NaiveClass
%NaiveClass what this will do is hold on his emails
% the p(message|class) compute the probability
% have the specific class info as well as who are they brothers
%
properties
name
numberOfMail
laplaceCounts
uniqueWords
totalMails
totalWords
likelihoodGivenClass
prior
end
methods
function identify(thisNaiveClass)
disp('I''m a bayes node')
end
function set = setPrior(obj)
obj.prior = (obj.numberOfMail + 1) / (obj.totalMails + obj.laplaceCounts)
end
function like = setLikelihood(this)
this.likelihoodGivenClass = (1 + 1) / (this.totalWords + 17)
end
end
end
But every time I call the function setPrior or setLikelihood the previous vaule get deleted from the other, the likelihood or the prior, like this:
>> setLikelihood(bayes)
this =
NaiveClass
Properties:
name: 'Primary'
numberOfMail: 3
laplaceCounts: 4
uniqueWords: []
totalMails: 12
totalWords: 8
likelihoodGivenClass: 2/25
prior: []
Methods
And then the other call:
setPrior(bayes)
obj =
NaiveClass
Properties:
name: 'Primary'
numberOfMail: 3
laplaceCounts: 4
uniqueWords: []
totalMails: 12
totalWords: 8
likelihoodGivenClass: []
prior: 1/4
Methods
So what is this?
Thanks.
You should listen to Mlint:
You are using the class as if it were a reference, but it does not inherit from handle. Quick fix:
classdef NaiveClass < handle
And then read this: http://www.mathworks.de/de/help/matlab/matlab_oop/comparing-handle-and-value-classes.html

solving the Chapman-Richards equation

I need to find a way to solve the Chapman-Richards with 3 parameters. The equation is
F=a(1-EXP(-bt)) power c
It is a nonlinear problem. The goal is to minimize the error and the constraints are that the 3 variables must be >= 0.0001. Our current implementation uses Excel and the Solver plugin (GRG nonlinear method). But now, we need to implement all this without making use of Excel.
My questions are:
1. Is it possible to use MS Solver Foundation to solve this problem?
I have read some docs and understand that MS Solver Foundation uses either the Nelder Mead Solver or the hybrid local search solver to solve nonlinear problems. Does anyone know if my particular problem can be solved using these methods? And, will the results be same as using GRG nonlinear method of Excel's Solver addin?
If not, is it possible to implement the GRG nonlinear method of Excel Solver?
Is there any other way to implement this?
Thanks for your replies in advance.
kar
Addendum:
Sorry, I forgot to mention that t is the time variable. a, b, and c are the parameters which can be changed by the solver.
Yes, it can be done with the Nelder-Mead solver in Solver Foundation. Here is some example code in C#. Just make sure you reference the Microsoft.Solver.Foundation assembly.
private const double t = 1.0;
public static void Main()
{
var solver = new NelderMeadSolver();
// Objective function.
int objId;
solver.AddRow("obj", out objId);
solver.AddGoal(objId, 0, true);
// Define variables.
int aId, bId, cId;
solver.AddVariable("a", out aId);
solver.AddVariable("b", out bId);
solver.AddVariable("c", out cId);
// Define bounds.
solver.SetLowerBound(aId, 0.001);
solver.SetLowerBound(bId, 0.001);
solver.SetLowerBound(cId, 0.001);
// Assign objective function delegate.
solver.FunctionEvaluator = FunctionValue;
// Solve.
var param = new NelderMeadSolverParams();
var solution = solver.Solve(param);
Console.WriteLine("The Result is " + solution.Result + ".");
Console.WriteLine("The minimium objective value is " +
solution.GetValue(objId) + ".");
Console.WriteLine("a = " + solution.GetValue(aId) + ".");
Console.WriteLine("b = " + solution.GetValue(bId) + ".");
Console.WriteLine("c = " + solution.GetValue(cId) + ".");
Console.ReadKey();
}
private static double FunctionValue(INonlinearModel model, int rowVid,
ValuesByIndex values, bool newValues)
{
var a = values[model.GetIndexFromKey("a")];
var b = values[model.GetIndexFromKey("b")];
var c = values[model.GetIndexFromKey("c")];
return a * Math.Pow(1.0-Math.Exp(-b * t), c);
}
I solved it with Visual Studio 2013 and Visual Basic, there is the traslation of the code.
Private Sub NelderMead()
Dim Solver As New Microsoft.SolverFoundation.Solvers.NelderMeadSolver
Dim objId As Integer
Solver.AddRow("obj", objId)
Solver.AddGoal(objId, 0, True)
Dim aId, bId, cId As Integer
Solver.AddVariable("a", aId)
Solver.AddVariable("b", bId)
Solver.AddVariable("c", cId)
Solver.SetLowerBound(aId, 0.001)
Solver.SetLowerBound(bId, 0.001)
Solver.SetLowerBound(cId, 0.001)
Solver.FunctionEvaluator = AddressOf FunctionValue
Dim Par As New Microsoft.SolverFoundation.Solvers.NelderMeadSolverParams
Dim Solucion = Solver.Solve(Par)
Debug.Print(Solucion.Result)
End Sub
Function FunctionValue(Model As Microsoft.SolverFoundation.Services.INonlinearModel, _
rowVid As Integer, _
Values As Microsoft.SolverFoundation.Services.ValuesByIndex, _
newValues As Boolean) As Object
Dim a, b, c As Double
a = Values(Model.GetIndexFromKey("a"))
b = Values(Model.GetIndexFromKey("b"))
c = Values(Model.GetIndexFromKey("c"))
Return a * Math.Pow(1.0 - Math.Exp(-b * t), c)
End Function