Wrong output value of Legacy Code Tool's Sfunction - matlab

I am getting wrong result of the example published in the Mathworks documentation in the link
I am expecting the output to be 2 times the sine wave of amplitude 1, but I am getting constant value of large magnitude in the order of 1e8.
I used the following commands:
def = legacy_code('initialize');
def.HeaderFiles = {'myfunc.h'};%,'mat.h'};
def.SourceFiles = {'myfunc.c'};
def.SFunctionName = 'sfun_myfunc';
def.OutputFcnSpec = 'double y1 = myfunc(double u1)';
def.Options.singleCPPMexFile = false;
legacy_code('sfcn_cmex_generate', def);
legacy_code('sfcn_tlc_generate', def);
legacy_code('compile', def);
legacy_code('slblock_generate', def);
What am I missing ?

I found the problem. In the header file, instead of using #ifndef I used erroneously #ifdef.

Related

'pie' function in MATLAB gives "undefined function 'cos'" error

I wrote a function, wins_plot, to read the scoreboard from a file and store the player's name, number of plays, wins, & losses. I stored all those using struct. I loop over the file, store each line in line, textscan for everything I need from line, and then iterate i (initially == 1) as I go to expand my array of structures. A snippet from the code to represent what I am saying:
c = textscan(line, '%s %s %d %d %d');
player(i).firstName = c{1};
player(i).lastName = c{2};
player(i).plays = c{3};
player(i).wins = c{4};
player(i).losses = c{5};
After all the file has been scanned and stored, I then write this code to extract the number of wins of each player and store it in X and then finally use the pie function to represent the values in X
for n=1:(i-1)
X(n) = player(n).wins;
end
pie(X);
I get a wall of error after:
Undefined function 'cos' for input arguments of type 'int32'.
Error in pol2cart (line 22) x = r.*cos(th);
Error in pie (line 99)
[xtext,ytext] = pol2cart(theta0 + x(i)*pi,1.2);
Error in wins_plot (line 30) pie(X);
I have no clue what might be wrong. Any help would be greatly appreciated. Please keep in mind that I only just started learning MATLAB today so my knowledge of it is very limited (and I have R2013a). Thank you in advance!
The numbers got read as int32, but when you call pie, it requires them to be double to do the computation. So, when you call pie, try casting the values to double. Try this,
pie(double(X));

not enough argument, self-defined function in matlab

I am a newbie of matlab and am trying to define a pretty complex function to plot it. The content of file is following:
function [res] = distribution (input)
a = factorial(30)
b = factorial(input) * factorial(30-input)
c = power(0.05, input)
d = power(0.95, 30-input)
a/b*c*d
end
in the file named distribution with .m extension. But when I run it error returns: "Error using distribution (line 4). Not enough input arguments."
I read through the "Getting Started" and find no solution. Does anyone have suggestions on this?
The name of the single argument to your function distribution(..), namely argument input, conflicts with the existing native input command of Matlab,
input: Prompt for user input.
...
x = input(prompt)
Try choosing a different name of this argument (in example below: foo), and also remember to return your result by assigning it to the return variable res:
function res = distribution (foo)
a = factorial(30);
b = factorial(foo) * factorial(30-foo);
c = power(0.05, foo);
d = power(0.95, 30-foo);
res = a/b*c*d; % <--- note, return parameter assignment
end

matlab How to use a textstring as input parameter in functions

I would like to use a dataset filename "AUDUSD" in several functions. It would be easier for me, just to change the filename "AUDUSD" to a more general name like "FX" and then using the abbreviation "FX" in other_matlab functions, e.g. double(). But matlab does not know the name "FX" (that should be assigned to the dataset "AUDUSD") in the code below... Any suggestions?
CODE:
FX = 'AUDUSD';
load(FX); %OKAY !!! FX works as input to open file AUDUSD!
Svars = {'S_bid','S_offer'};
Fvars = {'F_bid','F_offer'};
vS = double(FX,Svars); % FX does NOT work as input for the file AUDUSD
There is no double() function that accepts multiple cell arrays as arguments (this is what happens when you call double(FX,Svars)).
If you call double(FX), then each character in FX is interpreted for its ASCII value and then cast to double. So you get [ 65.0 85.0 68.0 85.0 83.0 68.0 ]. This is the behavior for the double() function if you provide a vector: each individual value in the vector is cast to double.
You'd have to provide more details on what you're trying to accomplish to give any more suggestions.
I have a different example, maybe you will better understand my point. The key work I would like to process is as follows:
I have got a folder with "dataset" files. I would like to loop through this folder, entering in any datasetfile, extracting the 2nd and 3rd column of each dataset file, and constructing only ONE new datasetfile with all 2nd and 3rd columns of the datasetfiles.
One problem is that the size of the datasetfiles are not the same, so I tried to translate a datasetfile into a double-matrix and then consolidate all double matrices into ONE double matrx.
Here my code:
folder_string = 'Diss_Data/Raw';
FolderContent = dir(folder_string);
No_ds = numel(FolderContent);
for i = 1:No_ds
if isdir(FolderContent(i).name)==0
file_string = FolderContent(i).name;
file_path = strcat(folder_string,'/',file_string)
dataset_filename = file_string(1:6);
load(file_path); %loads the suggested datasetfile; OKAY
M = double(dataset_filename);% returns an ASCII code number; WRONG; should transfer the datasetfile into a matrix M
vS = M(:,2:3);
%... to be continued
end
end

How to save a svm file in mexopencv

So, I am about to train a classifier and needed to save the result from the classifier, in mexopencv.
hello = cv.SVM;
hello.save('foo.xml')
My Matlab compiler crashes due to segmentation fault. As far as I know this is supposed to be the way in OpenCV. Is there any other way to save files trained via SVM in mexopencv ; or is this something to do with Matlab file writing option. Thanks.
This is in fact a bug in OpenCV itself, not mexopencv. You should report it...
Here is a minimal C++ program to reproduce the bug:
#include "opencv2/opencv.hpp"
#include "opencv2/ml/ml.hpp"
using namespace cv;
int main()
{
Ptr<SVM> svm = new SVM();
svm->save("svm.xml");
return 0;
}
Running this under a debugger, I located the offending code:
df_count = class_count > 1 ? class_count*(class_count-1)/2 : 1;
df = decision_func;
cvStartWriteStruct( fs, "decision_functions", CV_NODE_SEQ );
for( i = 0; i < df_count; i++ )
{
int sv_count = df[i].sv_count;
...
}
At this point, the SVM model is untrained, and df is an uninitialized pointer. class_count equals 0, but df_count gets set to 1, hence df[i] (with i=0) causes an access violation...
I think this could be fixed as:
df_count = class_count > 1 ? class_count*(class_count-1)/2 : 1;
if (class_count == 0) df_count = 0;
Changing df_count to 0 during debugging, the program runs correctly and I get the following XML file:
svm.xml
<?xml version="1.0"?>
<opencv_storage>
<my_svm type_id="opencv-ml-svm">
<svm_type>C_SVC</svm_type>
<kernel>
<type>RBF</type>
<gamma>1.</gamma>
</kernel>
<C>1.</C>
<term_criteria>
<epsilon>1.1920928955078125e-007</epsilon>
<iterations>1000</iterations>
</term_criteria>
<var_all>0</var_all>
<var_count>0</var_count>
<sv_total>0</sv_total>
<support_vectors></support_vectors>
<decision_functions></decision_functions>
</my_svm>
</opencv_storage>
For now you could avoid the bug by training the model first before saving it to file :)
You can try libsvm which has a Matlab interface. It comes two functions to read and write in svm (libsvmwrite and libsvmread).

Error using minus in MATLAB

temp(i,1) = rand(1)*(pb(1,num).pos(i,1) - pw(1,num).pos(i,1));
This line gives the following error:
Error using ==> minus
Not enough input arguments.
The following are the definitions of pb and pw.
pw=struct('fitness',[],'pos',{});
pb=struct('fitness',[],'pos',{});
pos is a 2 x 1 array.
When tracking down errors like this, I break the problem up into smaller bits. Especially when the logic isn't readily apparent. Not only does it provide a path that can be used to step through your function using the debugger, but it also makes it more readable.
I've taken liberty with the intermediate variable names.
thisPb = pb(1,num);
thisPw = pw(1,num);
initialPos= pw.pos(i,1);
finalPos = pb.pos(i,1);
whos initialPos finalPos
temp(i,1) = rand(1) * (finalPos - initialPos);
The line with whos will print out the values. Make sure that finalPos and initialPos are both numbers.
One way that you can get this error is when num is an empty matrix.
The expression
>> s(x).a
can return a variable number of outputs, depending on the size of x.
If x = [1,2,3] for example, it will return three values (as long as s has at least three elements).
If x = [] on the other hand, then s(x).a will return no outputs, so the expression
>> disp(s(x).a)
will give you a Not enough input arguments error, which is almost certainly what you're seeing. You should check that num is not empty.
Are you sure, that all values are really initialised? Try to check this before your codeline.
disp(pb(1,num).pos(i,1))
disp(pw(1,num).pos(i,1))
temp(i,1) = rand(1)*(pb(1,num).pos(i,1) - pw(1,num).pos(i,1));