Showing posts with label matlab. Show all posts
Showing posts with label matlab. Show all posts

Thursday, 20 August 2009

Matlab: Mex example in C way

There is a yprime.c for mex in Matlab. Here I translate to C, in order to understand mex better.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static void yprime(
double* yp,
double* y
)
{
double r1,r2;

double mu = 1/82.45;
double mus = 1 - 1/82.45;

r1 = sqrt((y[0]+mu)*(y[0]+mu) + y[2]*y[2]);
r2 = sqrt((y[0]-mus)*(y[0]-mus) + y[2]*y[2]);

yp[0] = y[1];
yp[1] = 2*y[3]+y[0]-mus*(y[0]+mu)/(r1*r1*r1)-mu*(y[0]-mus)/(r2*r2*r2);
yp[2] = y[3];
yp[3] = -2*y[1] + y[2] - mus*y[2]/(r1*r1*r1) - mu*y[2]/(r2*r2*r2);
return;
}

int main(){
double yo[4];
double yi[4] = {100, 2, 3, 4};

yprime(yo, yi);
printf("print out %f",yo[0]);



// some conversion practice
double a = yi[0];
char t1[7],t2[8],t3[8];

*t1= (char) a;
strcpy(t2,t1);

printf(strcat(t1, t2));

gcvt(a,7,t3);
puts(t3);

// i = sprintf(str, "%d", 15); //for interger to string


return 0;
}

Wednesday, 22 July 2009

16-bit binary data interpreting difference between Java and Matlab

The 16-bit data will be interpreted as different values in Java and Matlab. WHY??

Here are some experiments: save number 15 to 8-bit and 16-bit binary files, and another 259 in 16-bit binary files (refer to : this post).
======================

In Matlab (fread(fid1, 'uint8');): 15

16 bit bin file containing 15:
In WinHex: 0F 00
In java (DataInputStream.readShort();): [3840, 0]
=> 3840/256=15;
=> so, it's a kind of [15 00]
In Matlab (fread(fid1, 'uint16');): 15

16 bit bin file containing 259:
In WinHex: 03 01
In java (DataInputStream.readShort();): [769, 0] //Note, for every byte, java can

contain a value larger than 256, while other programming language will increment.
=> 769%256 = 1; 769/256=3.0039;
=> so, it's a kind of [03 01]
In Matlab (fread(fid1, 'uint16');): 259

Therefore:
========================
Therefore, a integer value in the range of 16-bit, for example 41837. In Matlab,

it will be intepreted as 41837, mod(41837,256)=109, 41837/256=163.4. So 41837 can

be displayed as [163 109] = 163*256+109; while java intepret [163 109] as

163+109*256 = 28067;


Conclusion:
========================
This seems wrong inside Java, but Java know how to process such value and export

it correctly to another bin file, which one can be understood by Matlab, WinHex or

other programming languages or editor.

Monday, 26 January 2009

Jython and Matlab do jobs for java

Java codes:
======================
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyExample
implements ActionListener {

public void actionPerformed(ActionEvent e) {
System.out.println("Ouch!");
}

public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setSize(300,300);
JButton button = new JButton("Push Me!");
ActionListener listener = new MyExample();
button.addActionListener(listener);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}


Jython:
======================
import javax.swing as swing

def printMessage(event):
print "Ouch!"

frame=swing.JFrame("my frame")
frame.setSize(300,300)
button=swing.JButton("Push Me!")
button.actionPerformed=printMessage
frame.getContentPane().add(button)
frame.setVisible(True) #frame.visible=1


Matlab:
=======================
import javax.*;

frame = swing.JFrame('my frame');
frame.setSize(300,300);
button = swing.JButton('Push Me!');

set(button,'ActionPerformedCallback',@printMessage);

frame.getContentPane.add(button);
frame.setVisible(true);

%code for sub function:
function printMessage(handle,event)
disp('ouch');
end

Wednesday, 7 May 2008

Matlab bugs about call external programs, such as Python

When I upgrade my OS to Ubuntu 8.04 and Matlab to Matlab 2008a, which is a fantastic version with a lot of optimizations and bug fixes.

But when I run my Matlab scripts, which using [system('python temp4python.py')] to do more system level jobs, I was prompted such a error message I've never seen before:/usr/local/matlab/sys/os/glnx86/libstdc++.so.6: version `GLIBCXX_3.4.9' not found (required by......

Why?
This similar message (or something like it) means that the loader is
linking to the versions of libstdc++ libraries supplied with Matlab,
and those versions do not correspond to the versions that your version
of Python was compiled against.


The fix!
(for me) was to navigate to the offending folder (/usr/local/matlab/sys/os/glnx86)
and make a new directory "old", and move all libstdc and libgcc files
into the "old" directory. Once done, the loader will be unable to link
with these libraries, and will be forced to use the ones installed in
your distribution instead.

Thursday, 27 March 2008

Two examples of matlab implement java

Example 1: print a line
===================
import java.lang.System;
System.out.println('zhengxin');

% in Java environment, java.lang.* is automatically imported, so no need to import it when programming with java. But in Matlab, this package/classes must be imported manually.


Example 2: show a dialog
===================
import java.awt.*;
import javax.swing.*;

title = 'Frame Title';
frame = JFrame(title);
comp = JTextArea();
frame.getContentPane.add(comp, BorderLayout.CENTER);
width = 300;
height = 300;
frame.setSize(width, height);
frame.show();

Saturday, 1 December 2007

Matlab call java "class"

1. Every methods should be public, especially the constructor. Otherwise the class can not be called.
Programming only within java, not so strict. Even you don't need put any identifier in front classes and functions.

2. Matlab and Sun Java are not compatible completely, though 99% do, especially when Sun Java or Matlab update, issues always come out. But I found Matlab call the java classes generated by gcc-java(gcj) works much better.
When Matlab updates, it almost work on or for latest java jdk. Matlab 2007a can not call the java class generated by jdk 1.6.03, while Matlab 2007b can.

3. Remember the javaclasspath variable in Matlab. To use javaaddpath(pwd) for you Matlab functions. If new class file is added, run clear;clc; again to initialize the new class.

3.2. About compiling
Put the class file in the static javaclasspath (which is set in /toolbox/local/classpath.txt), in this way it will much faster than javaaddpath(pwd). But you much also put the class file in the classpath of MCR, /toolbox/local/classpath.txt, in this file, there still saying "$matlabroot" things, but here $matlabroot is mean . Just put the class in the mcr classpath folder, no need to be same with .

4.Can not get the attributes from the returned object directly, you need to compose a getXXXX(){return XXXXXX} method by yourself.

5. mcc -m XX.m -a YY.txt
If the XX.m doesn't call java class (including Matlab embeded java functions, here try to use import less, which always cause error when the m-file is compiled), the YY.txt added by mcc without format changed will be able to be accessed, it is stored in XX_mcr/XX/. If not, the YY.txt can not be accessed. You must copy the YY.txt manually to the XX.exe folder.
Just be careful the added files when you mcc Matlab programs using java.

The attached code is to read config file abc.txt.
##################################
// GetConf.java
// GetConf.java
import java.util.*;
import java.io.*;

public class GetConf {
//the public is not necessary for Matlab, but for jython, this is essential.

String para;
Properties conf;

public GetConf() throws IOException{
conf = new Properties();
para = new String();
File file_name = new File("abc.txt");

FileInputStream conf_input;

try {
conf_input = new FileInputStream(file_name);
conf.load(conf_input);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}

public String getOnePara(String pnm){
para = conf.getProperty(pnm);
para = para.trim();
return para;
}

public static void main(String[] args) throws IOException{
String pa = (new GetConf()).getOnePara("a");
System.out.println(pa);
}

}
##################################
Here is the config file abc.txt
-------------------------------------------------
# a comment
! a comment

a = a string
b = a string with escape sequences \t \\ \" \' \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e = another string
------------------------------------------------

Wednesday, 28 November 2007

Symbolic Operations in Matlab

Background Note:

Up to this point we have done purely numerical operations in Matlab. This is the traditional approach for solving problems on the computer, and much of the current computational work done in industry follows this approach. However, a relatively new capability (last 5-10 years or so) that is gaining popularity involves the use of symbolic operations directly on the computer. Computer programs that use these symbolic techniques are often referred to as computer algebra systems, and they are becoming quite powerful. In particular, Matlab’s Symbolic Math Toolbox offers this general capability within the Matlab environment by providing an interface to the Maple code (Maple is a commercial software package that emphasizes symbolic manipulations or computer algebra techniques). This set of labs will introduce some of the basic symbolic capability in Matlab, eventually leading up to the analytical solution of Ordinary Differential Equations directly on the computer. Many of the exercises given here are derived from the Matlab’s User’s Guide and you are encouraged to refer to that manual for further examples and guidance.

Define Some Symbolic Variables:

First define a bunch of symbolic variables: syms a1 b1 c1 a2 b2 c2 d2 A B C1 C2 x y t

Now let’s form some symbolic functions:

Mathematical Function
Matlab Syntax for Function


f1 = a1 + b1*x + c1*x^2


f2 = a2 + b2*x + c2*x^2 + d2*x^3


g = exp(A*t)*(C1*cos(B*t)+C2*sin(B*t))


u = 2*x*y^2 + sin(x+y)


Differentiation of Symbolic Functions:

Differentiate each of the above functions using Matlab’s diff command. For example, try diff(f1). What happened? Is the result correct? Do the same thing for the other functions. What happens when you type diff(u)? How do you get Matlab to take the partial derivative with respect to the variable y? Type help sym/diff to see the various options associated with taking symbolic derivatives.

We can also take higher order derivatives. For example diff(f1,2) takes the second derivative of f1(x). Try this for all the functions!

Can you show that the mixed partial derivatives of u(x,y) are equal? Take du/dx and du/dy as above and save the results as string variables. For example, try typing

dudx = diff(u,x); dudy = diff(u,y);.

Now take the first derivative of these symbolic variables, as follows:

uyx = diff(dudx,y); uxy = diff(dudy,x);

Are these latter two variables the same? They should be. Pretty neat stuff, don’t you think!!!

Integration of Symbolic Functions:

Using Matlab’s int function, perform the following integrals using f1(x):

Mathematical Operation
Matlab Syntax for Operation


I1 = int(f1)


I2 = int(f1, 0, 5)


Do these make sense? Check out the subs command. Now let a1 = 1, b1 = -2, and c1 = 1, and substitute these numerical constants into the symbolic expressions for I1 and I2, as follows:.

I1 = subs(I1,{a1 b1 c1},{1 -2 1}), I2 = subs(I2,{a1 b1 c1},{1 -2 1})

What are the values for the integrals I1 and I2? Why is I1 a function of x and I2 is simply a scalar number? Note also that the curly brackets in Matlab refer to cell arrays. The sequence given by the set, {a1 b1 c1},{1 -2 1}, replaces the numerical variables into the symbolic variables in sequence. The cell array simply let’s us make all three substitutions in one call to the subs command.

Try integrating and substituting values for the constants in the other functions. Note that with u(x,y), you can only integrate with respect to one variable at a time. For example,

Mathematical Operation
Matlab Syntax for Operation


Iu = int(int(u,x,0,pi),y,0,2*pi)


Pretty impressive!!! Could you do this integral by hand this fast? I certainly can’t…

Plotting Symbolic Functions:

Certainly we can also plot symbolic relationships. Since we have already defined the constants for use with f1(x), let’s use this function to do some simple plots. In particular, let’s plot f1(x), df1/dx, and over the range . We can do this as follows:

F1 = subs(f1,{a1 b1 c1},{1 -2 1}); D1 = diff(F1); I1 = int(F1);
Nx = 51; xp = linspace(0,5,Nx);
F1p = double(subs(F1,x,xp));
D1p = double(subs(D1,x,xp));
I1p = double(subs(I1,x,xp));
plot(xp,F1p,’r-‘,xp,D1p,’g--',xp,I1p,’b-.’),grid
title(‘Evaluating and Plotting Symbolic Functions’)
xlabel(‘X Values’),ylabel(‘Various Function Values’)
legend(‘Function’,’First Derivative’,’Integral’)

Solving Algebraic Equations:

We can also solve algebraic equations with Matlab. For example, what if we wanted to know the value of x where f1(x) = 3? With the above constants this problem becomes: find x such that



In Matlab, we can use the solve command: solve(x^2-2*x-2) or solve(F1 - 3).

We can also solve systems of algebraic equations. For example, the analytical solution to the following 2x2 system:



is given by:

S = solve(3*x + 2*y - 3,-2*x + y + 7); % this solves a simple set of 2x2 equations

S.x, S.y % this prints x and y to the screen

Solving Ordinary Differential Equations:

The real goal of the above discussion and examples with symbolic variables is to give enough background so that we can solve ODEs analytically on the computer. This will be pretty powerful capability if we can actually do this with a set of relatively simple commands. As a test, let’s give Matlab’s dsolve command a workout for a few different types of ODEs that we have treated thus far in the semester (be sure to type help dsolve to get a good idea of the various forms that can be used).

a. Solve the first order IVP:



dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’x’) % this gives the general solution

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’y(1) = 0’,’x’) % this gives the unique solution

b. Solve the second order IVP:



Sh = dsolve('D2y - 4*y = 0','x'), pretty(simple(Sh)) % homogeneous soln
Sg = dsolve('D2y - 4*y = 4*x^2','x'), pretty(simple(Sg)) % general soln
Su = dsolve('D2y - 4*y = 4*x^2','y(0) = -1/2','Dy(0) = 4','x') % unique soln
pretty(simple(Su))

c. Solve the second order IVP:



Q1 = dsolve(‘D2y + 6*Dy +13*y = 10*sin(5*t)’, ’y(0) = 0’,’Dy(0) = 0’,’t’)
pretty(simple(Q1))

d. Re-solve the problem in Part c as a system of two 1st order ODEs, where z1 = y and z2 = dy/dt:



Q2 = dsolve(‘Dz1 =z2’,’Dz2 = -13*z1 -6*z2 + 10*sin(5*t)’, ’z1(0) = 0’,’z2(0) = 0’,’t’)
pretty(simple(Q2.z1)), pretty(simple(Q2.z2))

Final Note:

There is a lot of good stuff here. In particular, there are several examples that should make your life much easier in this course and in several of your other technical classes. You should do your best to understand the basic capability that is illustrated here -- it represents some pretty powerful mathematical analysis capability. You should also note that some of the examples from earlier in the semester (the Two Salty Tanks problem for example) give other illustrations of the use of computer algebra to solve a coupled set of first order differential equations for a real problem of interest. Also, a final Matlab demo will be given at the end of the semester illustrating how to take Laplace transforms and inverse Laplace transforms analytically using Matlab’s symbolic processing capability.

########
from: http://www.tmt.ugal.ro/crios/Support/ANPT/Curs/deqn/labs/mlabex_symbolic/mlabex_symbolic.html

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter