[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

MATLAB Programming

384

Solutions

456

Contributors

MATLAB is a numerical computing environment and proprietary fourth-generation programming language. MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, Java, Fortran and Python. Although MATLAB is intended primarily for numerical computing, an optional toolbox uses the MuPAD symbolic engine, allowing access to symbolic computing capabilities. An additional package, Simulink, adds graphical multi-domain simulation and model-based design for dynamic and embedded systems.

Share tech news, updates, or what's on your mind.

Sign up to Post

I cannot print to the command window when the Matlab Instance is launched with "matlabinit()".

I've tried (within the *.m file executed via MLEvalString()):
disp('show something');
fprintf('show something');

When I launch Matlab independently, "disp()" and "fprintf()" work just fine.

Any ideas?

Thanks in advance for your help.
0
CompTIA Network+
LVL 12
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Dear experts,

I am a chartered accountant, CIMA and CFA.

I have a lot of experience in writing excel formulae (the entire credit goes to this forum, thank you experts).

I now want to pursue Financial Engineering.

I am learning C, C++ now. Once I become well versed with these two languages, I will move to learning Python.

Now from robustness, depth and FE requirement is Python better or MATLAB

I am not sure I have the bandwidth to complete/learn both.

Till date I have been learning C and I did not struggle to pick up the synatax or logic.

Kindly advice.
0
I need to wrap a Fortran program to run from Matlab.  Has anyone done this before?  I did not find much information in my search.  Thank you for any help you can give.
0
I have an array (raw_acceleration) of 1600 elements acquired every 10 seconds at 160Hz from a sensor.
i use this array to calculate the fft and the Power Spectral Density and it works very well:


Fs=160;
raw_acceleration = u;
N = length(raw_acceleration);
xdft = fft(raw_acceleration);
xdft = xdft(1:floor(N/2+1));
psdx = (1/(Fs*N)) * abs(xdft).^2;
psdx(2:end-1) = 2*psdx(2:end-1);
freq = 0:Fs/length(raw_acceleration):Fs/2;

plot(freq,10*log10(psdx))
grid on
xlabel('Frequency (Hz)')
ylabel('Power/Frequency (dB/Hz)')

Open in new window


I obtain this plot:
psd-sand.png
As you can see, I obtain four peaks centered around four different frequencies.

I would like to have a Matlab code which is able to automatically find these four maximum peaks and their frequency.
At the moment, I always need to plot the graph and manually detect the maximum peak and its frequency.

Is there any way to do this by code?
I hope you an help me.

This is a sample of raw_acceleration array:

raw_acceleration= 
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0003
    0.0003
    0.0003
    0.0003
    0.0003
    0.0003
    0.0003
    0.0003
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0021
    0.0038
    0.0038
    0.0038
    0.0038
    0.0038
    0.0038
    0.0038
    0.0038
   -0.0002
   -0.0002
   -0.0002
   -0.0002
   -0.0002
   -0.0002
   -0.0002
   -0.0002
    0.0048
    0.0048
    0.0048
    

Open in new window

0
I have a set of seven parameters which are numerical values (i.e. current readings, pitch, roll and yaw angles, acceleration, etc..) and I use them to classify a vehicle behavior.
For example, if:

current=5A
pitch=12 degrees
yaw=41 degrees
Y_acc = 10 m/s^2
...

then the vehicle behaviour is classified as A otherwise if

current=7A
pitch=15 degrees
yaw=42 degrees
Y_acc = 11 m/s^2
...

then the vehicle is classified as B, and so on..

What is the best way to implement this kind of classification in Matlab?
Should I use a simple neural network? Or a classification method like SVM?
Is there any tutorial or example?

I have a set of data where each set of parameters is related to a specific behavior, so I can use this to train my model.

Thank you!
0
hi to all,

I have a vector in Matlab which contains samples acquired at 10Hz from an accelerometer mounted on a frame's vehicle.
This vector contains the acceleration values along the Z-axis.
The acquisition time is 103 seconds.

I would like to plot the frequency values in Hz since I'm trying to study the terrain frequency response.

I tried to use the fft function available in Matlab, but I do not know how to proceed.
Can you help me, please?

These are the values contained in my vector:

size(vibration)
ans =
        1024           1
vibration =
   -0.0005
   -0.0006
   -0.0007
   -0.0008
   -0.0010
   -0.0011
   -0.0012
   -0.0013
   -0.0014
   -0.0015
   -0.0016
   -0.0017
   -0.0018
   -0.0019
   -0.0020
   -0.0021
   -0.0022
   -0.0023
   -0.0024
   -0.0026
   -0.0027
   -0.0025
   -0.0003
   -0.0038
   -0.0089
   -0.0035
   -0.0018
   -0.0022
    0.0004
    0.0034
    0.0063
   -0.0023
   -0.0046
   -0.0022
   -0.0043
    0.0041
    0.0025
    0.0024
    0.0037
    0.0050
    0.0060
    0.0012
    0.0058
    0.0019
    0.0008
    0.0009
   -0.0060
    0.0004
    0.0032
   -0.0005
   -0.0008
   -0.0024
    0.0021
    0.0009
   -0.0019
    0.0003
    0.0012
    0.0069
    0.0125
    0.0209
    0.0262
    0.0184
    0.0100
    0.0058
    0.0136
    0.0181
    0.0089
    0.0058
    0.0077
    0.0045
    0.0024
    0.0015
    0.0044
    0.0095
    0.0096
    0.0087
    0.0019
    0.0053
    0.0066
    0.0033
   -0.0010
    0.0010
    0.0116
    

Open in new window

0
This code works for White particles on a black background, can it be tweaked to work for black particles on white background..?Thanks!

 
    RGB=imread('CW5000.jpg');
    s_wavelength=4; ; %use every 4th pixel for the perimeter calculation
    I = rgb2gray(RGB);
    threshold=.4 %black and white threshold
    bw = im2bw(I,threshold);
    imshow(bw)
    bw = bwareaopen(bw,350);
    se = strel('disk',2);
    bw = imclose(bw,se);
    bw = imfill(bw,'holes');
    [B,L] = bwboundaries(bw,'noholes');
    imshow(label2rgb(L, @jet, [.5 .5 .5]))
    hold on
    for k = 1:length(B)
    boundary = B{k};
    plot(boundary(:,2), boundary(:,1), 'y', 'LineWidth', 1)
    end
    stats = regionprops(L,'Area','Centroid','MajorAxisLength','MinorAxisLength')
    for k = 1:length(B)
    boundary = B{k};
    A = size(boundary)
    boundary2=boundary(s_wavelength:s_wavelength:A(1,1),:);
    delta_sq = diff(boundary2).^2;
    perimeter = sum(sqrt(sum(delta_sq,2)));
    area2 = stats(k).Area;
    area=polyarea(boundary2(:,1),boundary2(:,2));
    metric = 4*pi*area/perimeter^2;
    metric_string=sprintf('%2.2f',metric);
    text(boundary(1,2)+0,boundary(1,1)+50,metric_string,'Color','k',...
    'FontSize',12,'FontWeight','bold');
    %text(boundary(1,2)+40,boundary(1,1)+100,metric_string2,'Color','c',...
    %'FontSize',12,'FontWeight','bold');
    %text(boundary(1,2)+30,boundary(1,1)+150,metric_string3,'Color','g',...
    %'FontSize',12,'FontWeight','bold');
    

Open in new window

0
Hi to all,

I have a vector " imu" with a size of 11497 elements. These elements are samples captured at a very high rate (the total time is 71 seconds so I think the frequency is about 160 Hz). Since I acquired all the other values at 10Hz, the size of all my other vectors is 719.

I would like to remove the oversampled elements from the vector " imu" in order to have only 10 samples per second.

Is there any way to do this? Can you help me, please?
0
Hi to all,

i'm having a problem with one of my old matlab scripts.
This script worked very well on a previous version of Matlab, but now I'm running it on a different machine and on a different Matlab version (R2017b) and it gives me this error:

Index exceeds matrix dimensions.
Error in cusum (line 36)
y   = x1(:,c_y) - mean(x1(:,c_y));
Error in original (line 269)
      [ckc,slc]=cusum(Ic(:,2)); %% PROBLEMA 

Open in new window


Please, can you try to help me?
I attached to this post all the matlab files (i renamed them with *.txt extension) and also the txt file to use to populate the vectors.

The main matlab file is 'original.m':

clear all, close all
addpath '/home/rocco/Documents/MATLAB/code/function'
% 
% figure(1)
% set(1,'units','normalized','position',[0.142187 0.484722 0.307813 0.447222],....
%         'name','Path','numbertitle','off');
%     set(gca,'FontSize',11);
% figure(2)
% set(2,'units','normalized','position',[0.457031 0.484722 0.264063 0.447917],....
%         'name','Equivalent track','numbertitle','off');
%     set(gca,'FontSize',11);
%     
% figure(3)
% set(3,'units','normalized','position',[0.009 0.13 0.482031 0.806944],....
%         'name','Terrain estimation','numbertitle','off');
%     set(gca,'FontSize',11);
%     
% figure(4)
% set(4,'units','normalized','position',[0.00351563 0.0465278 0.214453 0.893056],....
%         'name','Path','numbertitle','off');

%% Load data

% First campaign january 2015

Open in new window

0
When I compile my mex with the "-g" argument, a PDB file is created which allows me to Attach to the Matlab Process.

This works OK.

However, I'm finding that if I change any part of the source code, then recompile the mex and Attach to Matlab again, my breakpoints are not ever hit again.

The solution is to exit Matlab, restart Matlab, rebuild the  mex and re-attach.  Then, magically, it works again.

But it's a royal pain to have to continue exiting Matlab every time I make a small code change.

Does anyone know what the solution is?

Thanks,
0
Exploring ASP.NET Core: Fundamentals
LVL 12
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Hi,
I am trying to check integration using two different methods, first by using [function (int)] and second by using summation. I am integration from high to low values (0.1 to 0). I got same result. However, from function I got positive value (0.005) and from summation, negative value (-0.005).  I am not sure if that because I am integrating from high to low values so I need to use (dr) in negative value when finding the integration using summation.

I used below code

 
 clear all;
  clc;
  syms x y 
  y = -x; 
  z=int(y,x);
  v=[0:0.1/19:0.1];
  dr=0.1/20;
  for i=1:20
      x=v(i);  
      kk(i)=eval(y)*(dr);    
  end
  R1=sum(kk(1,:));
  x=0.1;
  z1=eval(z);
  x=0;
  z2=eval(z);
  R2=z2-z1;

Open in new window

0
Hi,

I have a covariance matrix and I am using Matlab's chol function for cholesky decomposition. However, since my matrix is not a positive definite matrix. I am getting an error. How can I figure out which correlations/covariances in the matrix are leading to the problem.

Attached file contains the matrix.

Thanks
EE1.xlsx
0
As a part of my project, I want to encrypt user defined data using an unbreakable encryption algorithm. I have got one AES algorithm. But it accepts plaintext as
 plaintext_hex = {'00' '11' '22' '33' '44' '55' '66' '77' ...
                 '88' '99' 'aa' 'bb' 'cc' 'dd' 'ee' 'ff'};
I am doing my project in matlab.
0
Question :You are to simulate the motion of a drunken sailor (i.e. a random walk problem).  The sailor is standing at the middle of a pier on the shore side.  The sailor’s ship is directly across from him.The pier size is L paces long and W paces wide (i.e. the sailor starts at coordinates ½ W, 0 and the ship is L paces away) and the ship stretches across the entire width of the pier.Due to the sailor’s inebriated condition a straight walking path cannot be maintained.  Each second the sailor attempts to take a step.  There is a 25% chance that the sailor will go left, a 20% chance the sailor will go right, a 10% chance the sailor will stand still, and a 45% chance the sailor will go forward.  Assume the sailor does not go backwards.If the sailor’s position exceeds the dimensions of the pier (zero to W) they fall into the sea.  If they make it to the other side they are safe at their ship.Write a  Matlab program(script file) that takes L and W as user inputs.  The motion of the sailor is then simulated.  If the sailor falls into the sea an appropriate message should be output.  If the sailor makes it to the ship the time and number of paces it took them should be output.  For either case a plot showing the sailor’s path should be made.
Hint: Use evenly distributed random numbers to determine what direction the sailor goes.
0
Hi

I have .csv file with two cols . I need to take 13 values from 1st col then 13 values from 2nd cols and make then as one row with 26 col

until the end of file .
zju_25_5.csv
0
I want to find dct of a matrix in c++ just like how it is done in matlab.
Below is the code I used
#include <fftw3.h>
using namespace std;
 double** create2DArray(int row, int col)
{
	 double** arr = new  double*[row];
	for(int i = 0; i < row; i++)
		arr[i] = new  double[col];
	return arr;
}

int main()
{
int m = 3; 
int n = 3;
 	
      /*double a[m][n] =
   	 {
        {0.2, 0.3 ,1},
        {0 ,12 ,5},
        {0.3, 0.3, 1}
   	 };*/

   double** a= create2DArray(m,n); 
   for( int j = 0; j < m;j++ ) 
  	{	
  		for(int i = 0; i < n; i++)
	   		{	
    						a[i][j] = Signal[i]*hamming[i];
			}
  	 }

   double** b= create2DArray(m,n);   
   
    printf("Original vector\n");
	for(int i=0;i<m;i++)
	 {    
	  for(int j = 0 ;j<n;j++)
	     {
	        cout << a[i][j] <<"  " ;
	     }
	cout<< endl;
	}
  
    

    fftw_plan plan = fftw_plan_r2r_2d(n, m,&a[0][0],&b[0][0], FFTW_REDFT10, FFTW_REDFT10, FFTW_ESTIMATE);
    fftw_execute(plan);
      
    printf("DCT\n");
    for(int i=0;i<m;i++)
	{    
	for(int j = 0 ;j<n;j++)
		{
	cout << b[i][j] <<"  " ;
		}
	cout<< endl;
	}

    
    fftw_plan plani = fftw_plan_r2r_2d(n, m,&b[0][0],&a[0][0], FFTW_REDFT01,  FFTW_REDFT01,FFTW_MEASURE);
     fftw_execute(plani);
    
    printf("IDCT\n");

    
   	for(int i=0;i<m;i++)
	{    
	for(int j = 0 ;j<n;j++)
		{
	cout << a[i][j]/(m*n*4) <<"  " ;
		}
	cout<< endl;
	}
   
  
    return 0;
    

Open in new window


1) Matrix a[m][n] is obtained by multiplying signal with hamming window .
2) When I pass Matrix "a" as input to     " fftw_plan plan = fftw_plan_r2r_2d(n, m,&a[0][0],&b[0][0], FFTW_REDFT10, FFTW_REDFT10, FFTW_ESTIMATE); "
I get the following error :
 cannot convert ‘long double*’ to ‘double*’ for argument ‘4’ to ‘fftw_plan_s* fftw_plan_r2r_2d(int, int, double*, double*, fftw_r2r_kind, fftw_r2r_kind, unsigned int)’

How do I pass a matrix  to DCT function using fftw3 ,which is declared as mentioned above .
PS :When I declared it as double a[m][n] = {//Enter the elements}; //when m =640 ; n = 645
It gives Segmentation fault
{Because of which I tried to define matrix a in heap as mentioned but when given to the dct function throws error .}

Can anyone kindly solve my issue .
Thanks in Advance.
0
So I was trying to convert my matlab codes to c++ codes .I was trying to compare the output of all the user defined function written in matlab and c++ . In terms of precision there was slight difference . Something like   " 0.0822219583523415  " the output from matlab   and " 0.082222" from c++ . I ignored such difference at first as the result was similiar to some extent .But when operations like DCT and IDCT is done on vectors with such difference in values , the output I obtained from matlab and c++ DCT /IDCT was very different .
How can I solve this problem ?
0
First of all thank you for your help in advance. My question is regarding Matlab and non-linear Least Square curve fitting in Matlab - in both I am not familiar with.

I have this type of data:

x = [600, 800, 1000, 1200, 1400]; 
y = [0, 02, 04, 0.7, 1];

Open in new window


I am trying to use the following algorithms:

f = @(p,x) (p(3)-p(4))./(1+exp(-(x-p(2))/p(1)))+p(4); 
opts = optimset('Display','off','MaxFunEvals',1000); 
sigfit = lsqcurvefit(f, starting_value, intervals,problong,[],[],opts); 
bisection_point= sigfit(2)-sigfit(1)*log((sigfit(3)-0.5)/(0.5-sigfit(4)))

Open in new window


The only problem I have is the starting value in sigfit variable. What would be the best starting values given the above numbers? Any help please would be extremely appreciated.

The above algorithms are based on lsqcurvefit function found in Matlab. Here is the link: http://uk.mathworks.com/help/optim/ug/lsqcurvefit.html

The X vector is time intervals in milliseconds, whereas the Y vector represents responses some participant made whether those intervals where perceived as close to a short (400ms) or long (1600ms) interval.

I don't understand what starting points mean. Ultimately what I need to do is find the 0.5 point in the Y axis and the corresponding value on the X axis. The solution will be somewhere between 600ms to 1400 ms and probably around the 1200ms mark. I have put the starting value as a vector from 600 to 1400 but, I have no idea whether that is right or what that means. I was hoping someone better equipped than me can help answer this problem precisely :).

Thank you again,
Dritan
0
1) The MS Office I used for over 4 years was removed because W10 said that this "starter" office could cause damage.

2) Matlab starts up really fast. But when I enter a command and hit return, the command window gets stuck. In the admin account (which I rarely use), Matlab worked. (I will try re-installing it to see if that helps.) If you have any other suggestions other than reinstalling, I will give them a try.

I ran from the command prompt:
 slmgr /xpr
 and the popup said that Windows is permanently activated.
0
OWASP: Threats Fundamentals
LVL 12
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Let's say I already have a function like this
function Result = z(x, y)
Result=-x*y;

Open in new window

Given that function I want to solve this ODE. (the RHS comes from that function)
>> dsolve('Dy=-x*y','y(0)=2','x')
ans =
2*exp(-x^2/2)

Open in new window

However I don't want to update the second bit of code every time the first changes. I was wondering if there's a way for the result to be automatically updated.
0
As an example I could type this to solve an equation analytically
>> dsolve('Dy=-x*y','y(0)=2','x')
ans =
2*exp(-x^2/2)

Open in new window

I would like to evaluate this result numerically eg typing f(2) and the previous result (2*exp(-x^2/2)) would evaluated at 2 giving 0.2707
I could copy paste the previous result and make a a function like this, but I would prefer it to be automatic, otherwise I have to copy paste every time the original function changes.
function y = f(x)
y=2*exp(-x^2/2);

Open in new window

0
I need to implement the equation in attached picture in matlab. It involves 2 summations from 0 to infinity and bessel functions, and I am not sure if I am doing it correctly. Below is my code for the summations. The results I get for the final C value of the whole equation seem reasonable. However, I am questioning my implementation because I have to break out of the loop when my bessel functions evaluate to too large or small. I was wondering if anyone can comment on that, thank you.

sumn = 0;
sumnP = inf;
n = 0;

while abs(sumnP - sumn) > 1e-16
    % m-summation
    summ = 0;
    summP = inf;
    m = 0;
    while abs(summP - summ) > 1e-16
        summP = summ;
        if besseli(2*m+1,(2*n+1)*pi*a/L) ~= 0
        summ = summ + (cos(2*m+1)*ksi*cos(2*m+1)*delta/((2*m+1)^2))...
            *besseli(2*m+2,(2*n+1)*pi*a/L)/besseli(2*m+1,(2*n+1)*pi*a/L);
        else break
        end
        m = m + 1;
        if isnan(summ)
            summ = summP; break;
        end
    end
    sumnP = sumn;
    sumn = sumn + (-1)^n*sin((2*n+1)/2)*(pi*len/L)*summ;
end
equation.jpg
0
Is  there some application that can Convert C# to MATlab ?
0
In MATLAB I need to parse or split the following string 'E4'.  I want to be able to split 'C4' and 'C3' and compare the two numbers.  How can I do this?
Thanks
0
Experts,

So, I'm trying to repackage a MATLAB MCR, which is a compressed file that unpacks before it installs, using AdminStudio Repackager. I'm getting this line in the conversion:
"No INSTALLDIR definition was found in the options.ini file" - which is true...
Which results in an unsuccessful build, in the end. From my research, it's something about building from/to root C (C:\), but I'm working out of C:\Packages.

Any ideas?
0

MATLAB Programming

384

Solutions

456

Contributors

MATLAB is a numerical computing environment and proprietary fourth-generation programming language. MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, Java, Fortran and Python. Although MATLAB is intended primarily for numerical computing, an optional toolbox uses the MuPAD symbolic engine, allowing access to symbolic computing capabilities. An additional package, Simulink, adds graphical multi-domain simulation and model-based design for dynamic and embedded systems.

Top Experts In
MATLAB Programming
<
Monthly
>

No Top Experts for this time period. Answer questions to earn the title!