﻿ Matlab_It technology blog_ Programming technology Q & A「QuestionBank」
QuestionBank

### Matlab Difference between "Serial Send" and "To Instrument" blocks

The Instrument Control Toolbox in MATLAB/Simulink contains two blocks that can send data to a device on a serial port: Serial Send: Send binary data over serial port To Instrument: Send simulation data to instrument It looks like the To Instrument block is more general-purpose than Serial Send. To Instrument allows you to select the underlying interface, with one option being "Serial". What is the difference between To Instrument (when configured with Interface=Serial) and Serial Send? Is

### Matlab Imread resizes tif file

so I'm using the imread function in matlab and when I save the TIFF file and open it in photoshop, it has a white border and I can't understand why. I want to maintain its resolution as a 512 by 512 image. Any ideas why? And how I can fix that? Here's a sample code: B = imread('W_noise1.tif'); for n = 1:5, B = medfilt2(B); end B = filter2(fspecial('average',3),B)/255; imshow(B)

### Matlab How can I calculate the mean and maximum value for 4D image data?

I have some 4D image data, 384-by-276-by-20-by-5, where data(X,Y,T,V), X = x location, Y = y location, T = time, V = vessel location. I would like to have a mean value over time and maximum value over time for the data to get the pattern of my signal and thus set the value of my threshold value. I do it in loop so I could get say, for example data(1,1,:,1), a mean value for that point over time. I tried mean(data(X,Y,:,V)) and mean(squeeze(data(X,Y,:,V))) but it is giving me the error "Subscri

### Matlab Solving a delay differential equation (DDE) system constrained to give nonnegative solutions

In MATLAB, ode45 has a parameter called NonNegative which constrains the solutions to be nonnegative. They even wrote a paper about how this method works and how it's not something as stupid as just setting y_i to 0 whenever it becomes negative, as that won't generally work. Now, MATLAB also has dde23 for solving delay differential equations, but there is no equivalent NonNegative parameter for this integrator. Unfortunately, I am tasked with adding a delay to an existing ODE system which is s

### Matlab How to store fig in .mat file?

Is it possible to store the matlab figure inside a mat file, where the variable are stored. I got into a scenario where i generated some plot from the variable stored in the mat file. Currently im storing the figure as a separate file, this means, i have a 1 file for variables and another file for figure. But i would like to bundle them together in a single file.

### Matlab standard test videos for video processing

So.. In image processing, lena is the standard image for testing out algorithms in the research community. Similarly.. Are there any standard videos for testing out MATLAB codes for video processing?

### Pass variable from GUI to function in MATLAB

I have a MATLAB GUI that loads to aid in visually pre-processing data. Essentially it prompts the user to adjust the data range, reduce number of data points, etc... all while providing an updated graph. Upon completion of this work, I want to be able to close out the GUI and pass variables from the GUI to another MATLAB function that does the data analysis. I have found lots of information on how to pass information from a function TO and GUI, but not the other way around. Any help would

### string matching in an alpbetically ordered list (the MATLAB way)

I have a large alphabetically ordered cell array of strings (~495 thousand), with lots of duplicates (which are next to each other, because it's alphabetical). For a given look-up string, I need to find all the strings in the list which will match the one I pass in. I've been using strcmp(lookUpString,list) to do this, but this is extremely slow-- I think it's going through each value in the list to compare, because it doesn't know it's alphabetically sorted. I could write a while loop to ite

### How to vectorize this algorithm, octave verses matlab speed issue

Background story: This is an old script, I needed to compare two slightly different images of the same object to get data on the camera itself. I wrote this script in octave and tried it, later I found out matlab ran much faster with it so since than I used matlab instead of octave. I recently decided to check octave again, and I still got 1:1000 speed ratio. Questions: How can I vectorize this algorithm? Does matlab (verses octave) have a way to Auto-vectorize this code to run 1000 times fa

### matlab: making script to analyze data from excel file

I am analyzing data from a behavioral experiment. I am reading my data from one excel file into matlab. % load data [num,text,raw] = xlsread('stop'); data=num(:,10); % column 10 in original excel file The variable called data is a one-column vector (25000x1) containing results from all subjects. data(1:227) is from subject 1. data(228:420) is from subject 2, and so on. See a part of my data below: Subject ID Data 10011 384 10011 290 10011 508 10033 322

### Matlab Find Values in cell array of struct

I have two cell array's with structure in it. example: xmlFB = Columns 1 through 5 [1x1 struct] [1x1 struct] [1x1 struct] [1x1 struct] [1x1 struct] xmllink = Columns 1 through 3 [1x1 struct] [1x1 struct] [1x1 struct] xmlFB{1} ans = Param: {[1x1 struct] [1x1 struct]} InterChartConnection: [1x1 struct] Tasks: [1x1 struct] Attributes: [1x1 struct] xmllink{1} ans = Attributes: [1x1 struct] In "xmllink" there is the s

### Matlab: sort an array to ascending order in terms of binary interpretation

The array contains binary numbers per line: one row means one binary number. They are in no order so I am trying to find a command by which I can sort them to ascending order, how to do it? Input >> [1 0 0 1 1; 0 0 1 0 0; 1 0 1 0 0] ans = 1 0 0 1 1 0 0 1 0 0 1 0 1 0 0 0 0 0 0 1 Goal: by which command I can get by the input the below output? 0 0 0 0 1 0 0 1 0

### generate simple sine wave in matlab

How do I generate a simple sine wave in matlab? I would like to generate a wave which represents a temperature signal with an amplitude of 15 degrees during a 24 hour period, how can I do this? t = 1:24 x = 15.*sin(pi*t) plot(t,x) where 15 is the amplitude. This does not generate a sine wave as I expected. I was expecting to see one wave which extends over a 24 hour period with an amplitude of 15, say with the lowest value of 5 and a maximum of 20 (how do I include these in the equation?).

### matlab gui - callling the same gui screen

I'm trying to do in matlab, GUI that the the user enters points as input and connection between them. I have 5 matlab files - screen1.m, screen2.m, screen3.m, screen4.m, globalParams.m in globalParams I have global params so I can use them from screen GUI to screen GUI. in screen1 the user enters the number of nodes(for example 5). when he press the Next button the callback function calls "screen2();". in screen2.m the user enters the (x,y) coordiante and when he press the Next button the call

### Matlab relationship between peak value and rms

suppose that we have following signal: Compute the RMS level of a 100-Hz sinusoid sampled at 1 kHz. t = 0:0.001:1-0.001; X = cos(2*pi*100*t); it's spectrum is plot(periodogram(X)); now if i want to to calculate magnitude of peak,i know that there is some relationship between root mean square(RMS) and amplitude for sinusoidal models,form this site http://www.indiana.edu/~emusic/acoustics/amplitude.htm Example: The rms of a sine wave with a hypothetical peak-to peak value of –1 to

### Matlab Find major axis of an ellipse

I have an image which contains an ellipse(a cell), I am trying to work out its major and minor axis. I know I have to work out the major axis first and possibly the foci points before this, but I'm not sure how to go about this exactly. I don't know how I should cycle through the image to obtain the measurement and how to correctly identify the major axis if I did. If anyone can offer any information on how to go about doing this it would be a great help.

### Matlab Interpreting neurons in the neural network

I have come up with a solution for a classification problem using neural networks. I have got the weight vectors for the same too. The data is 5 dimensional and there are 5 neurons in the hidden layer. Suppose neuron 1 has input weights w11, w12, ...w15 I have to explain the physical interpretation of these weights...like a combination of these weights, what does it represent in the problem.Does any such interpretation exist or is that the neuron has no specific interpretation as such?

### Access RGB channels in an image in MATLAB

I want to access the red channel of each pixel in my image. I don't want to change it. I just want to identify the pixels with a range of red. I'm looking for pixels that will have the colors like RGB(15,0,0), RGB(120,0,0), RGB(200,0,0) and so on. My image is mostly gray, I want to identify the red boxes on that. I tried: image = imread('myimage.jpg'); figure; imshow(image); redPlane = image(:,:,1); figure; imshow(redPlane); The second figure displayed is all gray. It took off the red.

### Plotting with a For loop in Matlab

I've made a code which uses a for loop to determine values of ti and t. When I plot the variables I get all my points as a scatter plot and I want to plot a line of best fit as the data in linear. However, the data is being plotting as each point being their own data set. is there a way to collect the data into a matrix to plot a linear graph clc clear all close all %Heat Transfer % I is the current passing through the conductor I=475; % h is the coeffcient of convective heat [W/ m^2*K] tr

### Break loop efficiently when figure exited Matlab

I've always had the same problem, and I'd really like to know if there's a solution to it. If I do something like: figure axis([-2 2 -2 2]) a=1; h=rectangle('Position',[1,0,0.1,0.1]); t=0; while a==1 if ishandle(h) t=t+0.1; pause(0.001) x=0.2*cos(t); y=0.2*sin(t); set(h, 'Position', [x, y,0.1,0.1]) else break end end I always get some sort of error when the figure is exited with the x button: Error using handle.handle/set Invalid or deleted object. This isn't surprising, because if I exit

### After Using bwlabel in MATLAB,Can I change the labels of the connected components?

There are some white portions in a black object. I need to cover up the all the white portions in the object with its neighboring black. The bwlabel function labels the black part as '2' and white part as '1'. can i somehow change the labels of the required object and cover the white portion with black. I have isolated the objects individually using the following code: a=imread('3.jpg'); figure(),imshow(a),title('Original image'); b=im2bw(a, graythresh(a)); figure(),imshow(b),title('

### mex file compiled without errors but not working in matlab

First I wanted to compile MatConvNet library for using in windows form this tutorial (Compiling MatConvNet on Windows) but I couldn't. Then I think it is better to compile a very simple file and after that going to compile the library. I have Matlab R2013a 64 bit and Visual Studio 2010 64 bit. my program Test.cpp #include "mex.h" void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { printf("Hello! :)\n"); } I can compile Test.cpp in matlab with mex Test.cpp And

### Matlab Determining the number of occurrences of each word in cell array

I have huge vector of words, and I want a vector with the unique words only, and the frequency for each word. I've already tried hist and histc but they are for numeric value. I know the function tabulate but it gives the words some ' (e.g this turns to 'this'). If you have any idea how to do it MATLAB it would be great. thanks

### Set up linear programming code in Matlab to obtain vertices in 4D or higher dimensions

Suppose I have a point cloud given in 4D space, which can be set up arbitrarily dense. These points will lie on the surface of a polytope, which is an unknown object at this point. (Just to provide some unhelpful visualization, here is a rather arbitrary projection of the point cloud which I have given - i.e. plotting the first 3 columns of the 100000x4 array): My goal is to obtain the vertices of this polytope, and one of my numerous attempts to get those was computing the convex hull of the

### Matlab Displaying kmean result with specific colors to specific clusters

I applied k-mean clustering on a preprocessed image using the following matlab code %B - input image C=rgb2gray(B); [idx centroids]=kmeans(double(C(:)),4); imseg = zeros(size(C,1),size(C,2)); for i=1:max(idx) imseg(idx==i)=i; end i=mat2gray(imseg); % i - output image Every time I display the output, color assigned to the output images changes. How can I give a specific color to cluster1, cluster2, cluster3 and cluster4.

### how to calculate |a-b| in matlab ?

I tried searching for available functions but did not come across any. Is it same as calculating Euclidean distance between two points? Can |a-b| be calculated if a and b are matrices or vectors? Thanks.

### Matlab Using FastICA to split a signal bands based on frequency

I am trying to split the bands of a signal and I used butterworth filter and It worked fine but I need to know how can I split the bands of the signal using FastICA package. Any help?? Lets say I need to split it into 3 bands (band one : 1 - 5 Hz,band one : 6 - 10 Hz and band one : 11 - 15 Hz).

### Saving Blocks of cropped image Resulted from blockproc in Matlab

I've been trying to crop and save the blocks (subimages) from the original image using blockproc and imcrop functions, but I couldn't. I'm only able to see the figures of the blocks. Is there any way to save these blocks to the specified folder? Thanks. clear all close all clc a = imread('3.jpg'); folderPath='C:\Program Files\Folder'; blockSize = [70,70]; d = blockproc(a,blockSize,@(bs) imcrop(bs.data)); %blockproc(a, blockSize, @(bs)imcrop(bs.data),'BorderSize', [1 1 ]); %i=1; fileName = [fol

### Matlab Keep right to left text (Arabic - Hebrew - Farsi) when exporting to pdf

I can successfully display Right-To-Left text (Arabic - Hebrew - Farsi) in Matlab figures using the command text(.). However, saving it into PDF, the characters are printed from Left-To-Right again. How can I let Matlab keep it Right-to-Left when converting to PDF? Minimal example: fig = figure(1) set(0,'DefaultTextFontname', 'Arial') rectangle('position',[0,0,600,1435]); axis equal text(100,1200,'الكتاب','fontname','Arial', ... 'VerticalAlignment','middle','Horizont‌​alAlignment','l

### Matlab ODE with varying parameters

I am trying to do exactly what has been explained here: How solve a system of ordinary differntial equation with time-dependent parameters (part 2). Here is my code. I have no idea where I'm going wrong. function shi = shitry(t,y,b,bt) b = interp1(bt, b, t) a = 0.25; %loss of immunity rate % b = 0.0002; %infectivity rate q = 10; %population renewal m = 0.012; %death rate r = 0.14; %recovery rate shi(1) = q - m*y(1)-b*y(1)*y(2)+a*y(3); shi(2) = (b*y(1))- (m + r)*y(2); shi(3) = (r*y(2))-((m+a)*

### Matlab Grouping variable must be a vector Error in KNN Classifier

I am working on KNN classifier using matlab's function： knnclassify(gp,trainingClass, gpTest), where gp is <849x36 double> matrix , gpTest is matrix to test but it raises the following error Error using grp2idx (line 39) Grouping variable must be a vector or a character array. Error in knnclassify (line 81) [gindex,groups] = grp2idx(group); Error in test (line 1) knnclassify(gp,trainingClass, gpTest);

### Normalized histogram in MATLAB incorrect?

I have the following set of data: X=[4.692 6.328 4.677 6.836 5.032 5.269 5.732 5.083 4.772 4.659 4.564 5.627 4.959 4.631 6.407 4.747 4.920 4.771 5.308 5.200 5.242 4.738 4.758 4.725 4.808 4.618 4.638 7.829 7.702 4.659]; % Sample set I fitted a Pareto distribution to this using the maximum likelihood method and I obtain the following graph: Where the following bit of code is what draws the histogram: [N,e

### Is there any way that matlab write the results of calculations in text file?

I have simple calculation as below : syms a b c d e f A = [a,b;c,d;e,f]; B = pinv(A); Is there any way that matlab write the results of calculations in .m file or text file?

### Set the initial type of a vector in Matlab

I'd like to declare an empty vector that accepts insertion of user-defined types. In the following examples node is a type I've defined with classdef node ... The following code is rejected by the Matlab interpreter because the empty vector is automatically initialized as type double, so it can't have a node inserted into it. >> a = []; >> a(1) = node(1,1,1); The following error occurred converting from node to double: Conversion to double from node is not possible. The code belo

### Inverse fast fourier transform in MATLAB

My MATLAB code for fft and ifft below has a problem with the inverse Fourier signal y not matching the in put signal x. Is there any solution to resolve this? N = 1000; t0 = 1e-13; tau = 2*1e-14; n = [0:t0/40:2*1e-13-t0/40]; f0 = 3*1e8/(150*1e-9); x = cos(2*pi*f0*n); x = x.*exp((-(n-t0).^2)./(tau^2)); X = abs(fft(x,N)); F = [-N/2 : N/2 - 1]/N; X = fftshift(X); y=ifft(X,80); figure(3) plot(n,y)

### Matlab Pushbutton zoom in and zoom out in GUI

I need code to pushbuttons "zoom in", "zoom out" for my image. Trying to used this but wrong. Please, help me. I work with the MATLAB Gui. function btnZoomIn_Callback(hObject, eventdata, handles) uicontrol('Style','pushbutton','String','ZoomIn','Units','pixels',... 'Position',[90 10 60 20],'Enable','off',... 'Tag','btnZoomIn','Callback',@btnZoomIn_Callback); h = guihandles(hObject); set(h.btnZoomOut,'Enable','on') data = guidata(hObject); data.magnif = data.magnif+1; guidata(hObject, data)

### Matlab Assignment has more non-singleton rhs dimensions than non-singleton subscripts error

When I run this code, it appears that: "Assignment has more non-singleton rhs dimensions than non-singleton subscripts". The errors start from the line "BEXC(i,j,k,1) = i*0+j*0+(0.5+(k-1))*BE2A*cos(BETA/180*pi)"

### Matlab - Plot difference between two graphs in specific points

I have two graphs, one is the exact graph of a solution, the other is a numerical approach. I have 4 specific points in my figure (t=0.25,0.5,0.75,1), where I want to illustrate the difference between the two graphs with a straight line. I found the errorbars function but i don't see any use there. Hope you can help me! Edit: this is the example figure: t = [0:0.25:1]; y = t.*4; x = t.^2+3; plot(t,y,t,x) I have 4 points now, t=0.25; t=0.5; t=0.75; t=1; At this points, I just want a v

### Matlab cputime with kmeans return 0

I am measuring the cputime taken by kmeans algorithm for each iteration using cputime feature. However, some iterations return cputime = 0. Here's my implementation: load fisheriris; [~,C] = kmeans(meas, 3, 'options',statset('MaxIter', 1),'Display', 'off'); results=[]; for i = 1:15 t=cputime; [~,C] = kmeans(meas, 3, 'options',statset('MaxIter', 1),'Start',C, 'Display', 'off'); elapsedCPUTime=cputime-t; results=[results;elapsedCPUTime]; end

### How to sum a cell in Matlab

I am a new learner in Matlab and now want to add up a cell of column elements in Matlab, somehow "sum" function didn't work and it shows "Undefined function 'sum' for input arguments of type 'cell'", is there anyone know how to do it? MANY THANKS!:) my data is like this: '218148' '106856' '255673' '156279' '175589' '310762' '87128' '123339' '149070' '104556' '206346' '216278' '235786'

### How to scale two signals in Matlab

I would like to scale a signal (Sig) to its reference (Ref) by calculating the scaling factor. Usually, I calculate the scaling factor by dividing max(Ref) by max(Sig). But, it only works when both signals are starting from zero. How to scale, if the signals are as follows: Ref = [2 2 2 2 3 4 4 4 4 4 4 4 3 2 2 2 2 2 2 2 2 3 4 4 4 4 4 4 4 3 2 2 2 2]; Sig = [2 2 2 2 4 6 6 6 6 6 6 6 4 2 2 2 2 2 2 2 2 4 6 6 6 6 6 6 6 4 2 2 2 2]; This is my algorithm: maxSig = max(Sig); maxRef = max(Ref); sf = (

### Matlab How to find the angle between a line and a polyline?

How to find the angle between a line (formed by two points) and a polyline with MATLAB? polyline sample data: X = [59.5001826000000,59.5005297000000,59.5006135000000,59.5012631000000,NaN]; Y = [36.3160562000000,36.3158460000000,36.3157953000000,36.3153916000000,NaN]; two points sample data: p1 = [36.3083315600000, 59.5669254100000]; p2 = [36.3083643100000, 59.5667925800000];

### Matlab yyplot label and plot

I want to plot e_eff5(2) the imaginary and real part as undotted, normal line and the e_eff5(1) the imaginary and real part as dotted. The real parts are on the left size(blue), the imaginary on the right side(red). Then i want tolabel the 4 lines, dotted blue, normal blue, dotted red, normal red. i=1; for T = 20:5:25 teta = 1 - 300/(273.15 + T); e0 = 77.66 - 103.3 * teta; e_unendlich = 0.066 * e0; yd = 20.27 + 146.5 * teta + 314 * teta^2; %relaxation frequency e_eff5(i,:) = (e0 - e_unendlich

### Draw random numbers from the Gumbel distribution in Matlab

Question: I would like your help to draw random numbers from the Gumbel distribution with scale mu and location beta in Matlab. I want to use the definition of the Gumbel distribution provided by Wikipedia (see the PDF and CDF definitions on the right of the page). Notice: The package evrnd in Matlab, described here, cannot be used (or maybe can be used with some modifications?) because it considers flipped signs. Let me explain better this last point. Let's fix the scale to 0 and the lo

### Matlab How to sort through and map IVs to unique H values

H = [500 500 500 450 450 450 400 400 350 350 350 300 300 300]; I = [-0.0019 -0.0018 -0.0017 -0.0019 -0.0018 -0.0017 -0.0019 -0.0018 -0.0017] V = [-7.54E-06 -7.23E-06 -6.93E-06 -7.53E-06 -7.21E-06 -6.89E-06 -6.60E-06 -7.50E-06 -7.23E-06 -6.90E-06] Need to sort through the data and get an IV for each value but lump then off the uniqueness of their value, e.g., I want all the IVs for the H at 400, etc. I know there is a unique function in Matlab, but that only gives me a single element of the ar

### Matlab - how does contour plot generating levels automatically?

I am using contourf to generate filled contour plots on MatLab with specified levels number. According to the documents (https://www.mathworks.com/help/matlab/ref/contourf.html#mw_9088c636-4036-4e00-bd43-f6c5632b63ec) It says Specify levels as a scalar value n to display the contour lines at n automatically chosen levels (heights). I am wondering how does it choose the threshold automatically? What is the algorithm of choosing the thresholds? Take level as 1 as an example. Many thanks!

### Matlab How to obtain a solution of a set of coupled 4th order odes and algebraic equations

I have set of three equations that need to be solved simultaneously to obtain results for six variables. It is actually a system of equations with one 4th order equation and one algebraic equation. The details about the problem description: I have written the code for this problem by unsuccessfully linking ODE with other two equations as: %.......Define Guess values for Two algebraic equations No.2 and 3.........% global gus_value mass_flux_save gus_value =[0.0001, 334]; mass_flux_save=[];

### Matlab Struct contents reference from a non-struct array object

I want to create a loop to delete file within specific file size and I have these problems. selpath = uigetdir(files) for ii = 1:length(files) if files(ii).bytes<500000 % 500kb delete(fullfile(files(ii).folder, files(ii).name)) end end and I always got this message >> cobayginibro selpath = 'D:\Proyekan Tes' Struct contents reference from a non-struct array object. Error in cobayginibro (line 3) if files(ii).bytes<500000 % 500kb Any idea how to

### Matlab How to fix "if statement" issue in my code?

Here is my code. I want P_ABP and P_ACP values to be zero if they are smaller than 0. But I still get negative values when I plot the graph. day = 40; angle_mu = 8; lat = 30.43; Ps = 1000; elev = 59.9; time = linspace(0,24,24); alpha = 360/24*(time-12); dec = 23.44sind(360(day-80)/365.25); zen = acosd(sind(dec).*sind(lat)+cosd(dec).*cosd(lat).*cosd(alpha)); tan_azi = atand(sind(alpha)./sind(lat).*cos(alpha)-cosd(lat).*tand(dec)); azi = atand(tan_azi); for i = 1:length(alpha) if alpha(i) >

### What is the best way to build a model of automated system with neural network in Simulink (Matlab)?

I'm tring to build a model contating neural network in Simulink. My idea is to compose a model which includes a controlled object (electrical drive), PID controller and NN block for fine-tuning of the PID controller. NN training is provided for to be the reinforcement learning. NN calculates the koefficients of the PID controller, then it receives the feedback from the output of the object and calcucales the koefficients for the next cycle to minimize the static error. I've build the model witho

1    2   3   4   5   6  ... 下一页 最后一页 共 276 页