http://www.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2015-06-30T21:26:34Ztag:www.mathworks.com,2005:Question/1604452014-10-28T17:01:15Z2015-06-30T21:26:34ZMicrosoft Kinect V2 with Matlab<p>Hallo,
I would like to use the <b>Microsoft Kinect V2</b> with the Matlab <b>Image Acquisition Toolbox</b> . Is this possible or do I have to use the <b>Kinect V1</b> model?</p><p>Thanks a lot!</p>Wilfriedhttp://www.mathworks.com/matlabcentral/profile/authors/4186187-wilfriedtag:www.mathworks.com,2005:Question/2259682015-06-30T20:32:34Z2015-06-30T21:26:05ZAssigning colors to different lines in one plot<p>Hello,</p><p>I am currently working on some code to create and format subplots. Would anybody be able to help with the following problem: a portion of my code is designed to create a subplot with 3 lines in the single plot (6:2:10). How can I go about assigning a color to each of these lines? Below is the section of my code attempting to run this command</p><p>figure(2),
Colors = ['r', 'g', 'b'];
c=1;
subplot(121), hold on, %this makes a subplot and plots every other column from 6-10
for i = [6:2:10]
plot(data(6:end,i), 'Color',[0.36 0.0 0.0]);
c=c+1;
end</p>fabricio saucedohttp://www.mathworks.com/matlabcentral/profile/authors/4840394-fabricio-saucedotag:www.mathworks.com,2005:Question/2228032015-06-07T00:45:51Z2015-06-30T21:25:56ZHow to fit 6 curves simultaneously to solve for 2 unknowns?<p>y=(1-exp(-0.5*Phi*Gain*(x-TimeDelay)^2))*Amax</p><p>Gain and TimeDelay are unknown. x is time (T1-T6) and y is response (F1-F6)(source of noise). Phi is different for each curve, and Amax is constant.</p><p>Attached is a sample dataset. The values for Phi and the Amax for this dataset are found to the right of the data.</p><p>I tried the Curve Fitting Toolbox, but it seems to be designed for one trace at a time. I can get the curves to fit for the first 4 traces but not the last 2. However, I need to get one gain value and one TimeDelay that is the best (or least bad) fit across all traces. I don't know what function to use.</p><p>Thank you! Any help is appreciated.</p><p>***note: I am editing the question with the comments from Walter taken into consideration. I initially typed the equation incorrectly (wrote Amax was negative and it isn't) and I also thought TimeDelay was constant and it isn't.</p>Delores Davishttp://www.mathworks.com/matlabcentral/profile/authors/5358337-delores-davistag:www.mathworks.com,2005:Question/2259732015-06-30T21:23:26Z2015-06-30T21:23:26ZHow to embed MCR in Matlab Compiler using "mcc"?<p>I know that using the deploy tool you can select "Add MCR" then "Embed the MCR in the package". However, is there a way to do this using the command "mcc" instead of deploy tool.</p><p>Where I work QA likes us to create a sort of "make" file that has the mcc command string. So we can attach it in our configuration management software. So using mcc is preferred over deploy tool.</p><p>Thanks for any help!</p>Benhttp://www.mathworks.com/matlabcentral/profile/authors/6660879-bentag:www.mathworks.com,2005:Question/2256842015-06-28T23:12:20Z2015-06-30T21:22:54ZLego Mindstorms NXT Support Package<p>Hi all
I can´t install the Lego Mindstorms NXT Support Package. I have the student license of my University. On the other side, I've installed the Arduino Support package without any problem (for discarding that the problem is the licence or login, the connection or something related) I've added an image with the failure message. I don't have any MathWorks strange directory, as I've checked in other forums that it could be the problem.</p><p>Thank you in advance.</p>MCarmenhttp://www.mathworks.com/matlabcentral/profile/authors/4808507-mcarmentag:www.mathworks.com,2005:Question/2254982015-06-26T16:58:49Z2015-06-30T21:22:26Zanother question has come up about hist3()<p>OK. So, I have access to the statistics toolbox now. And, I was wondering how I would go about plotting the hist3 function for the same code from:</p><p><a href = "http://www.mathworks.com/matlabcentral/answers/224847-how-to-create-bins-that-are-then-used-to-create-surf-function">http://www.mathworks.com/matlabcentral/answers/224847-how-to-create-bins-that-are-then-used-to-create-surf-function</a></p><p>Because [N,C]=hist3(...) doesn't actually display a plot, and having something along the lines of the Seamount:Data Point Density Histogram and Intensity plot (link is below) would be extremely helpful.</p><p><a href = "http://www.mathworks.com/help/stats/hist3.html?refresh=true">http://www.mathworks.com/help/stats/hist3.html?refresh=true</a></p><p>Thanks again!</p>jgillis16http://www.mathworks.com/matlabcentral/profile/authors/5879134-jgillis16tag:www.mathworks.com,2005:Question/2259012015-06-30T11:52:24Z2015-06-30T21:19:08ZCross validation in recurrent neural network<p>There doesn't seem to be any facility to use cross-validation in recurrent neural networks in the NN Toolbox.</p><p>The following script is taken directly from the documentation on the 'layrecnet' function;</p><p>[X,T] = simpleseries_dataset;
net = layrecnet(1:2,10);
[Xs,Xi,Ai,Ts] = preparets(net,X,T);
net = train(net,Xs,Ts,Xi,Ai);
view(net)
Y = net(Xs,Xi,Ai);
perf = perform(net,Y,Ts)</p><p>Running this script starts the window, but no validation checks are made during training, and the process is stopped either by reaching the maximum epochs or mu value.</p><p>I've tried dividerand and divideind, but I cannot get validation checks to occur in any simulation.</p><p>Any suggestions?</p><p>Also, the example given in the documentation on Design Layer-Recurrent Neural Networks has the same problem. Is it a trait of recurrent neural networks that I was unaware of that validation checks cannot occur, am I doing something wrong, or is this a bug in the program?</p><p>Cheers,</p><p>Alex</p>Alex Chttp://www.mathworks.com/matlabcentral/profile/authors/6413881-alex-ctag:www.mathworks.com,2005:Question/2175652015-05-19T13:01:07Z2015-06-30T21:16:51Zsave large image/figure<p>I have a large mxn (~300,000 x 75) element matrix that I would like to save as an image or pdf without any compression. I'm currently using imagesc() to display. I've used the print function to set my own resolution but I'm having difficulty achieving the desired result. The image is a large time series that I would like to save in such a way that I may zoom in over a region, and transmit the complete series to others without any losses. Is there a simple method to save large , essentially banner sized, images / figures?</p>George Valdeshttp://www.mathworks.com/matlabcentral/profile/authors/6513857-george-valdestag:www.mathworks.com,2005:Question/2259722015-06-30T21:14:46Z2015-06-30T21:14:46ZEmbedded coder produces incorrect code reading from Simulink data store<p>I have a shared structure that holds the coefficients of a biQuad filter block. This is for a 10th order filter that is implemented as 5-2nd order sections (SOS). The structure is defined as:</p><pre class="language-matlab">typedef struct {
real_T numerator[3][5];
real_T denominator[2][5];
real_T gain[6];
} userFilterSOS5;
</pre><pre class="language-matlab">typedef struct
{
int16_T BP_LPsel; // [0 = DC, 1 = BPF] connects to LP input
int16_T LP_HPsel; // [0 = DC, 1 = BPF, 2 = LPF] connects to HP input
int16_T HP_notchSel; // [0 = BPF, 1 = LPF, 2 = HPF] connects to notch input
int16_T output_Sel; // [0 = BPF, 1 = LPF, 2 = HPF, 3 = notch] connects to output
int32_T DCdelay;
int32_T BPdelay;
int32_T LPdelay;
int32_T HPdelay;
int32_T N1delay;
int32_T N2delay;
int32_T N3delay;
int32_T N4delay;
real_T FIRbpfCoef[301]; // FIR filt has only numerator coefs
userFilter7 LPF;
userFilter7 HPF;
userFilterSOS5 notch1;
userFilterSOS5 notch2;
userFilterSOS5 notch3;
userFilterSOS5 notch4;
} filtersBus;
</pre><p>It is declared as:</p><pre class="language-matlab">filtersBusSig = Simulink.Signal;
filtersBusSig.DataType = 'Bus: filtersBus';
filtersBusSig.SamplingMode = 'Sample based';
filtersBusSig.Complexity = 'real';
filtersBusSig.InitialValue = 'filtersBusStruct';
filtersBusSig.StorageClass = 'ExportedGlobal';
</pre><p>In the Simulink DataStoreRead block, it is specified as:</p><pre class="language-matlab">filtersBusSig.notch1.numerator(:,:)
filtersBusSig.notch1.denominator(:,:)
filtersBusSig.notch1.gain(:,:)
</pre><p>The embedded decoder generates the following code to read the data out of the DataStore:</p><pre> /* DataStoreRead: '<S22>/notch1Coef' */
for (i = 0; i < 15; i++) {
decoder_decBPFpump_B.notch1Coef_o1[i] = filtersBusSig.notch1.numerator[i];
}</pre><p>We have tried this with the Visual Studio 2013 compiler, Intel compiler, and QtCreator compiler, and all of them generate something like the following error:</p><pre class="language-matlab">../decoder-common-lib/decoder_Main_Model/testRepo/slprj/ert/decoder_decBPFpump/decoder_decBPFpump.c:
756: error: incompatible types when assigning to type ‘real_T’ from type ‘real_T *’
</pre><p>I understand that the embedded coder likes to convert 2D arrays to 1D vectors, but this code will not compile.
Is there a way to correct this, or at least force it to generate a warning?</p>Seanhttp://www.mathworks.com/matlabcentral/profile/authors/3210708-seantag:www.mathworks.com,2005:Question/2259592015-06-30T18:43:22Z2015-06-30T21:03:50ZHow to get Matlab to unlock or release a directory?<p>I have scripts that create a temporary directory to store intermediate files created during processing. At the end of the scripts I want to clean this temporary directory out and remove the directory. I can remove the files that I create, but when I run the rmdir() command, it will usually fail with the message "MATLAB:RMDIR:SomeDirectoriesNotRemoved". If I go into the file system and do a "ls -al" command, I will see that there is a Matlab lock file or something in the directory. It will go away if I shut down Matlab. Unfortunately it's not easy to recreate, because I've tried creating a directory from the command line, adding, modifying and removing a few files, and then removing the directory and it always seems to work fine. Something about running my scripts as a whole is causing Matlab to lock the temporary directory, and I don't know a way to unlock it.</p>Scotthttp://www.mathworks.com/matlabcentral/profile/authors/688558-scotttag:www.mathworks.com,2005:Question/2259022015-06-30T11:54:58Z2015-06-30T21:03:41ZHow do I cross-validate in recurrent neural networks?<p>There doesn't seem to be any facility to use cross-validation in recurrent neural networks in the NN Toolbox.</p><p>The following script is taken directly from the documentation on the 'layrecnet' function;</p><p>[X,T] = simpleseries_dataset;
net = layrecnet(1:2,10);
[Xs,Xi,Ai,Ts] = preparets(net,X,T);
net = train(net,Xs,Ts,Xi,Ai);
view(net)
Y = net(Xs,Xi,Ai);
perf = perform(net,Y,Ts)</p><p>Running this script starts the window, but no validation checks are made during training, and the process is stopped either by reaching the maximum epochs or mu value.</p><p>I've tried dividerand and divideind, but I cannot get validation checks to occur in any simulation.</p><p>Any suggestions?</p><p>Also, the example given in the documentation on Design Layer-Recurrent Neural Networks has the same problem. Is it a trait of recurrent neural networks that I was unaware of that validation checks cannot occur, am I doing something wrong, or is this a bug in the program?</p><p>Cheers,</p><p>Alex</p>Alex Chttp://www.mathworks.com/matlabcentral/profile/authors/6413881-alex-ctag:www.mathworks.com,2005:Question/2259712015-06-30T21:01:36Z2015-06-30T21:03:39ZHow can I make a Neural Network with graphical inputs?<p>Hello everyone, first of all, I wanted to say that I am beginner using MATLAB and Neural Networks app, only knowing the basics. I am currently a researcher in biotechnology currently trying to diminish the costs of new-generation drugs.</p><p>I wanted to ask if it's possible using a Supervised Neural Network with graphical inputs. For example, I have 100 graphs resulting of a specific mouse behavior (depressed mouse for instance), and in the other hand I have more 100 graphs resulting from a happy mice.</p><p>With an unknown behaviour curve I want the percentage of "similarity" with the happy mice curves and depressed ones. Similar to what we get with the Breast Cancer and Wine Vintage pre-defined datasets that come with the app, but with the major difference of the graphical inputs instead of the normalized value per class.</p><p>Many thanks in advance,</p><p><i>Note 1: I have the curves in an excel and each one has more than 20 000 dots.
Note 2: I do not actualy work with mice, and used that example to simplify the question only. My curves are time vs energy, and my outputs are Ionic Exchange behavior and Hydrophobic interaction behavior.</i></p>Joao Cardosohttp://www.mathworks.com/matlabcentral/profile/authors/6660818-joao-cardosotag:www.mathworks.com,2005:Question/2259702015-06-30T21:00:09Z2015-06-30T21:00:09ZHow do I resolve "advanced graphics rendering error" prompt?<p>I recently installed the Feb 2015 commercial version of MATLAB with my work, but several local errors keep occurring, meaning I have the latest version of MATLAB of all my coworkers and only my PC is affected. The following warning usually shows up when I display certain images, plot data, or run certain scripts that have pictures:</p><pre> Warning: MATLAB has disabled some advanced graphics rendering features by switching to software OpenGL. For more
information, click here.</pre><p>When I click "here", it takes me to the "Resolving Low-Level Graphics Issues" documentation. So I ran</p><pre class="language-matlab">opengl info
</pre><p>and got the following:</p><pre class="language-matlab">Version: '1.1.0'
Vendor: 'Microsoft Corporation'
Renderer: 'GDI Generic'
MaxTextureSize: 1024
Visual: 'Visual 0x23, (RGB 24 bits (8 8 8), Z depth 16 bits, Software, Single buffe...'
Software: 'true (known graphics driver issues)'
SupportsGraphicsSmoothing: 0
SupportsDepthPeelTransparency: 0
SupportsAlignVertexCenters: 0
Extensions: {3x1 cell}
MaxFrameBufferSize: 0
</pre><p>So OpenGL <i>is</i> installed, I just don't know how to resolve my known graphics issues. It's not interfering with my work (yet), but I would like to know how to proceed. Thanks in advance</p>Alison Bowdenhttp://www.mathworks.com/matlabcentral/profile/authors/6660221-alison-bowdentag:www.mathworks.com,2005:Question/2259692015-06-30T20:46:10Z2015-06-30T20:46:10ZAdding rows up to a certain value (cell arrays) <pre class="language-matlab">I have a cell (curCell_res) which has two columns (column 1 is name and column 2 is the value). I need 230 from column2. This means I need to take everything from A1 to B5 (220) + 10 from C1.
'A1' 27.5
'A2' 16.5
'A3' 22
'A4' 22
'A5' 22
'B1' 27.5
'B2' 16.5
'B3' 22
'B4' 22
'B5' 22
'C1' 27.5
'C2' 16.5
'C3' 22
'C4' 22
'C5' 22
'D1' 27.5
'D2' 16.5
'D3' 22
'D4' 22
'D5' 22
I need to get to an answer cell that looks like this:
'A1' 27.5
'A2' 16.5
'A3' 22
'A4' 22
'A5' 22
'B1' 27.5
'B2' 16.5
'B3' 22
'B4' 22
'B5' 22
'C1' 10
I started writing the code:
DEMAND = 230;
for i = 1:size(BIG,1) %this is the BIG cell array from which curCell_res comes
curCell_res = BIG{i};
for k=1:size(curCell_res,1)
if k==1
Sum_Power(k) = curCell_res(k,2);
elseif k > 1
Sum_Power(k) = curCell_res(k,2) + Sum_Power(k-1);
if Sum_Power(k) > DEMAND
surplus = Sum_Power(k) - DEMAND; %surplus is not needed
not_surplus = curCell_res(k,2) - surplus; the needed bit we have to take
</pre><p>I have problems continuing, I don't know how to formulate the part where I store the the sequence of numbers and the names. Furthermore, I keep on getting errors such as "conversion from double to cell is not possible"... Can you tell me how I should proceed?</p>Eli Dimhttp://www.mathworks.com/matlabcentral/profile/authors/6630315-eli-dimtag:www.mathworks.com,2005:Question/2258352015-06-29T23:35:01Z2015-06-30T20:27:28ZIs it possible to evaluate a colon notation string without using the eval function?<p>In my pursuit of always trying to eliminate the use of the eval function in my code (whether it makes sense to do this or not), I am looking for a way to turn a string such as mystring = '[1:10]'; into the column vector myvector = [1 2 3 ... 10]; without using the eval function.</p><p>mystring could be '[1:10]', '[1:1:10]', '[2:2:140 146:2:260 123435]', or just about anything the user puts in there that will evaluate to a vector at the matlab command prompt.</p><p>The usage comes from reading a kind of input spreadsheet which contains a colon notation string for each row into matlab, and having matlab create the corresponding vectors. Currently this is done easily for each row with myvector = eval(mystring);. I can't think of a better way to do it... maybe it doesn't exist, but I'm all ears if anybody has some ideas.</p><p>I know there is a way to go the other way on the file exchange (vect2colon.m, by Javier Lopez-Calderon). Realistically, the biggest performance hit comes from reading the spreadsheet into Matlab rather than using the eval function, but I'm still curious about this question.</p>Ryanhttp://www.mathworks.com/matlabcentral/profile/authors/793592-ryantag:www.mathworks.com,2005:Question/2259672015-06-30T20:23:23Z2015-06-30T20:38:08ZOptimization problem - max independent given a function value<p>Hi I have the following:</p><pre class="language-matlab">syms irr2 m_S s
</pre><pre class="language-matlab">irr1=0.05;
M=0.7;
n=120;
</pre><pre class="language-matlab">f=(symsum(1/(1+irr1)^s,s,1,n)-symsum(1/(1+irr2)^s,s,1,n)*(1+M*m_S)/(1+irr2)^m_S);
</pre><p>f must be equal zero</p><p>m_S is a variable</p><p>I wanna know which is the max irr2 ... how can I do it?</p>Brunohttp://www.mathworks.com/matlabcentral/profile/authors/4113809-brunotag:www.mathworks.com,2005:Question/2211632015-05-29T21:51:52Z2015-06-30T20:16:20Zhow can use static feedforward neural network to predict futre observation<p>As newff the appropriate choice or we must use others functions like feedforwardnet???</p>coquihttp://www.mathworks.com/matlabcentral/profile/authors/5461334-coquitag:www.mathworks.com,2005:Question/2259552015-06-30T17:54:35Z2015-06-30T20:11:16ZHow to click stop a function in while loop using a pushbotton in GUI?<p>I have two buttons. When DC_start is pressed it disables itself and two user inputs, and then enters a while loop. At some point the user will click the DC_end button and it changes its value to 1 and the while loop is supposed to break.</p><p>A simplified version of the code is provided below with the error. Please let me know how to overcome this as its my first time making a GUI. I believe I have to use the uiwait function and suppress the warning, but even then I am confused at how to use the handle for the DC_end button if its not in the scope of the DC_start callback function.</p><p>If there is a completely different but better way to code this up. I'm open to suggestions.</p><p>Thanks in advance,
George</p><pre class="language-matlab">function DC_start_pushbutton1_Callback(hObject, eventdata, handles)
</pre><pre class="language-matlab">set(handles.DC_start_pushbutton1,'Enable', 'off')
set(handles.DC_numSamples_edit, 'Enable', 'off')
set(handles.DC_electrodesList_edit, 'Enable', 'off')
</pre><pre class="language-matlab">channelNum = 0;
dataEntry = 0;
endButton = get(handles.DC_end_pushbutton2,'Value');
</pre><pre class="language-matlab">while( ~isequal(endButton, 1))
endButton = get(handles.DC_end_pushbutton2,'Value');
channelNum = channelNum + 1; dataEntry = dataEntry + 1;
</pre><pre> pause(0.500);</pre><pre> if endButton == 1;
disp('Data collection canceled!')
break;
end
end</pre><pre class="language-matlab">disp('Done!');
</pre><pre class="language-matlab">function DC_end_pushbutton2_Callback(hObject, eventdata, handles)
set(handles.DC_end_pushbutton2,'Value',1)
</pre><p>Error Message:</p><pre class="language-matlab">Undefined function or variable 'ElectrodeGUI'.
</pre><pre class="language-matlab">Error in
@(hObject,eventdata)ElectrodeGUI('DC_end_pushbutton2_Callback',hObject,eventdata,guidata(hObject))
</pre><pre class="language-matlab">Error using pause
Error while evaluating UIControl Callback
</pre>Georgehttp://www.mathworks.com/matlabcentral/profile/authors/3513722-georgetag:www.mathworks.com,2005:Question/2259502015-06-30T17:43:51Z2015-06-30T20:09:13ZHow to copy content of of 7*14 matrix file(*.mat) to a table on Microsoft Word??<p>How to copy content of of 7*14 matrix file(*.mat) to a table on Microsoft Word??</p>rose rosehttp://www.mathworks.com/matlabcentral/profile/authors/3612391-rose-rosetag:www.mathworks.com,2005:Question/2259662015-06-30T20:01:32Z2015-06-30T20:01:32ZCombining [m;2] matrices of histogram data where values of m vary<p>My experience with Matlab is very limited, and any help is greatly appreciated.</p><p>I have histogram data for occurrences of various processes at different time increments. For example:</p><p>[time increments;occurrences]</p><p>[0 1 2 3;23 58 81 32] [2 3 4 5 6;15 56 91 72 5] [1 2 3 4;2 105 42 29]</p><p>I need to build a single matrix like this:</p><p>[time increments;occurrences;occurrences;occurrences]</p><p>[0 1 2 3 4 5 6;23 58 81 32 0 0 0;0 0 15 56 91 72 5;0 2 105 42 29 0 0]</p><p>I have read how to combine simple matrices, but I'm having trouble figuring out how to insert the zero values for time increments were there is no data. If it matters, the two column matrices have approximately 100,000 rows.</p>Justin Warrenhttp://www.mathworks.com/matlabcentral/profile/authors/6657165-justin-warrentag:www.mathworks.com,2005:Question/2255832015-06-27T16:44:21Z2015-06-30T19:58:12Zconditional mean and variance-co-variance matrix<p>I have 9 time series R, which is N*9 matrix. i would like to get conditional mean and variance for these time series. how can i write the code in matlab Under two different models? one is AR and GARCH, and another one is EWMA.
i also need conditional variance-Covariance matrix, how to write the code under both of models.</p><p>thanks</p>FEIhttp://www.mathworks.com/matlabcentral/profile/authors/3407138-feitag:www.mathworks.com,2005:Question/2258722015-06-30T09:29:24Z2015-06-30T19:57:57Zhow can we know the optimal solution from GA in MATLAB is the best solution? if all the results are always different from each other after run it in several times.<p>the optimum solutions from GA are always different after I run it in several time, so I wonder that which one is the best solution or how many time should I run it to make sure it the best solution ?
thank you very much.</p>Chantrea Leanhttp://www.mathworks.com/matlabcentral/profile/authors/6489790-chantrea-leantag:www.mathworks.com,2005:Question/2253202015-06-25T15:58:21Z2015-06-30T19:54:31Zmex setup .rvm resource temporarily unavailable<p>I am attempting to set up mex in Matlab to compile CUDA codes, and when I type</p><pre> mex -setup</pre><p>at the command line I get a long loop of statements saying variations of .rvm Resource temporarily unavailable, followed by fflush failed, standard output:Broken pipe for a few lines, and then back to statements about .rvm. I end up having to force quit Matlab, the command line won't respond to control-c. Anyone have any idea what's going on? I'm using Matlab R2015 and Mac OS X v 10.10.3</p>Andrew Harrishttp://www.mathworks.com/matlabcentral/profile/authors/4446011-andrew-harristag:www.mathworks.com,2005:Question/2259652015-06-30T19:54:19Z2015-06-30T19:54:19Zi want to draw 3 line plots in a single graph which shows distribution of data in 3 columns<p>the data file with sample graph is attached</p>lavanya sandeephttp://www.mathworks.com/matlabcentral/profile/authors/5309844-lavanya-sandeeptag:www.mathworks.com,2005:Question/2259642015-06-30T19:28:16Z2015-06-30T19:42:04ZHow to export data from matlab to csv file from loop?<p>I have a bunch of data from a for loop that I need to export from matlab to csv file. I tried csvwrite('test.xlsx',data). When I open up the csv file, the data for a single iteration comes up. How can I get the data from every iteration to export to the csv file?</p><pre class="language-matlab">if true
% code
end
fileFolder = fullfile(matlabroot, 'toolbox', 'images', 'imdata');
dirOutput = dir('/Users/JessFlores/Documents/MATLAB/XrayEye_*.tiff');
fileNames = {dirOutput.name}'
numFrames = numel(fileNames)
figure(); hold on
for p = 0001:numFrames
sequence(:,:,p) = imread(fileNames{p});
%intensity plot info
[x,y] = size(sequence(:,:,p));
X = 1:x;
Y = 1:y;
[xx,yy] = meshgrid(Y,X);
i = im2double(sequence(:,:,p));
</pre><pre> %maz and FWHM x and y from plot
[mz,k] = max(i(:));
[ix,jy] = ind2sub(size(i),k);
[ix,jy,mz];</pre><pre> %max intensity coordinates in microns
%pixel size is 6.45x6.45 microns
ix = 6.45*ix;
jy = 6.45*jy;
[ix,jy,mz];
mhz = 0.5*mz;
[ihx,jhy]=ind2sub(size(i),k);
[ihx,jhy,mhz];
FWHMx = abs(ix-ihx)*2;
FWHMy = abs(jy-jhy)*2;</pre><pre> %table of data from plot
f = figure;
data = [ix,jy,mz,FWHMx,FWHMy];
colnames = {'X(Zmax) [um]', 'Y(Zmax) [um]', ...
'Zmax/Max Intensity', 'FWHMx [um]', 'FWHMy [um]'};
t = uitable(f, 'Data', data, 'ColumnName', colnames, 'ColumnWidth', {120});
t.Position(3) = t.Extent(3);
t.Position(4) = t.Extent(4);</pre><pre> %make subplot of table and intensity plot
subplot(2,1,1) = mesh(xx,yy,i); colorbar;
title('Intensity of Beam Image as a Function of Pixel Position');
xlabel('X(pixels)');
ylabel('Y (pixels)');
zlabel('Intensity (double precision corrected) [a.u.]');</pre><pre> csvwrite('test.csv', data);
end</pre><p>hold off</p>Jessica Floreshttp://www.mathworks.com/matlabcentral/profile/authors/6450507-jessica-florestag:www.mathworks.com,2005:Question/2259342015-06-30T15:44:24Z2015-06-30T19:39:02Zusing Matlab to plot density contour for scatter plot<p>Hi guys, I'm trying to use Matlab to plot the density contour for the following scatter plot. The bins will be 1X1 box. Within my limited understanding the density contour should be indicated how many points fall into the bins(correct me if I'm wrong), but I still cannot find a way to do the density plot. Need some help to solve this problem. Thanks!</p><img src = "/matlabcentral/answers/uploaded_files/33461/figure.jpg">Keqiao Lihttp://www.mathworks.com/matlabcentral/profile/authors/5396151-keqiao-litag:www.mathworks.com,2005:Question/2253632015-06-25T20:04:31Z2015-06-30T19:35:31ZExporting data while 'live' processing in a GUI<p>Hi everyone,</p><p>The question pertains to the export of data from a GUI that is 'live' processing data from an incoming datastream. The initial question came from some work by Jerome, and is located here on his website ( <a href = "http://www.matlabtips.com/realtime-processing/">Link</a>.)</p><p>(In order to save time, I have the code from Jerome posted below as well. Please note that this script requires Image Acquisition Toolbox.)</p><pre class="language-matlab">function realVideo()
</pre><pre class="language-matlab">% Define frame rate
NumberFrameDisplayPerSecond=10;
</pre><pre class="language-matlab">% Open figure
hFigure=figure(1);
</pre><pre class="language-matlab">% Set-up webcam video input
try
% For windows
vid = videoinput('winvideo', 1);
catch
try
% For macs.
vid = videoinput('macvideo', 1);
catch
errordlg('No webcam available');
end
end
</pre><pre class="language-matlab">% Set parameters for video
% Acquire only one frame each time
set(vid,'FramesPerTrigger',1);
% Go on forever until stopped
set(vid,'TriggerRepeat',Inf);
% Get a grayscale image
set(vid,'ReturnedColorSpace','grayscale');
triggerconfig(vid, 'Manual');
</pre><pre class="language-matlab">% set up timer object
TimerData=timer('TimerFcn', {@FrameRateDisplay,vid},'Period',1/NumberFrameDisplayPerSecond,'ExecutionMode','fixedRate','BusyMode','drop');
</pre><pre class="language-matlab">% Start video and timer object
start(vid);
start(TimerData);
</pre><pre class="language-matlab">% We go on until the figure is closed
uiwait(hFigure);
</pre><pre class="language-matlab">% Clean up everything
stop(TimerData);
delete(TimerData);
stop(vid);
delete(vid);
% clear persistent variables
clear functions;
</pre><pre class="language-matlab">% This function is called by the timer to display one frame of the figure
</pre><pre class="language-matlab">function FrameRateDisplay(obj, event,vid)
persistent IM;
persistent handlesRaw;
persistent handlesPlot;
trigger(vid);
IM=getdata(vid,1,'uint8');
</pre><pre class="language-matlab">if isempty(handlesRaw)
% if first execution, we create the figure objects
subplot(2,1,1);
handlesRaw=imagesc(IM);
title('CurrentImage');
</pre><pre> % Plot first value
Values=mean(IM(:));
subplot(2,1,2);
handlesPlot=plot(Values);
title('Average of Frame');
xlabel('Frame number');
ylabel('Average value (au)');
else
% We only update what is needed
set(handlesRaw,'CData',IM);
Value=mean(IM(:));
OldValues=get(handlesPlot,'YData');
set(handlesPlot,'YData',[OldValues Value]);
end</pre><p>Imagine a case where you are tracking data from a webcam for an 8 hour session. In order to prevent the risk of losing all data in one save session at the end of the day, I would like to break the session into, say, 30 min sessions that I want to save, while still maintaining a display window active.</p><p>My initial thought was to save some maintain some type of a counter, where upon reaching 30 minutes, it would output a file (i.e. 'YData', [OldValues Value].) However, I am not sure if the write time can potentially have an impact on the data analysis/updating screen. Is this something that can be introduced in as a separate timerFcn?</p><p>I'm guessing that it's not the first time this question has been asked, so any direction/thoughts would be most appreciated.</p><p>Thanks.</p>Sidhttp://www.mathworks.com/matlabcentral/profile/authors/3187995-sidtag:www.mathworks.com,2005:Question/2259632015-06-30T19:28:09Z2015-06-30T19:29:26ZConnecting Simmechanics Blocks to Matlab functions<p>Hello There!</p><p>I would like to attach the block of my simmechanics model to a matlab function in order to retrieve the solid features into a matlab file (or function), so that I can play around with the geometry data in simulation. However when I try to connect the simmechanics block wth matlab functions, I get no success. Can somebody please tell a way to retrieve the block features into an m file (or function) right in the simulink space?</p><p>Thanks in advance.</p>Anamika Saxenahttp://www.mathworks.com/matlabcentral/profile/authors/5870228-anamika-saxenatag:www.mathworks.com,2005:Question/2259622015-06-30T19:20:46Z2015-06-30T19:20:46ZBuilding a GUI for a BeagleBone Black using MATLAB?<p>Ideally, I would like to run a stand-alone GUI MATLAB script on a BeagleBone Black.</p><p>Here's what I have:</p><p>>MATLAB R2015a for Windows 64-bit</p><p>>BeagleBone Black with embedded Linux</p><p>>Adafruit 2.8" TFT LCD touchscreen</p><p>I need to know if this is possible. If it is, some tips about how to get started would be wonderful. If it's not, what would be the easiest way to build a GUI application that could run on a BeagleBone Black? I am a beginner to all of this, so any information would be greatly appreciated.</p><p>-Ryan</p>Ryan Landryhttp://www.mathworks.com/matlabcentral/profile/authors/6658435-ryan-landrytag:www.mathworks.com,2005:Question/2259612015-06-30T19:15:54Z2015-06-30T19:15:54ZGPU training of neural network with parallel computing toolbox unreasonably slow, what am I missing?<p>I’m trying to speed up the training of some NARNET neural networks by using the GPU support that you get from the parallel computing toolbox but so far I haven’t been getting it to work. Or rather, it is working but it’s unreasonably slow. According to the documentation training on a GPU instead of the CPU shouldn’t be any harder than adding the statement 'useGPU','yes” to the training command.
However, if I simply create some dummy data, for example a sine wave with 900 values, and train a NARNET on it using the CPU like so:</p><pre class="language-matlab">%CPU training
T = num2cell(sin(1:0.01:10));
net = narnet( 1:2, 10 );
[ Xs, Xsi, Asi, Ts] = preparets( net, {}, {}, T );
rng(0)
net.trainFcn = 'trainscg';
tic
net = train(net,Xs,Ts,'showResources','yes' );
toc %2.77
</pre><p>The training takes less than 3 seconds. But when doing the exact same thing on a CUDA supported GTX 760 GPU:</p><pre class="language-matlab">%GPU training
T = num2cell(sin(1:0.01:10));
net = narnet( 1:2, 10 );
[ Xs, Xsi, Asi, Ts] = preparets( net, {}, {}, T );
rng(0)
net.trainFcn = 'trainscg';
tic
net = train(net,Xs,Ts,'useGPU','yes','showResources','yes' );
toc % 1247.6
</pre><p>Incredibly the training takes over 20 minutes!</p><p>I’ve read through Mathworks fairly extensive documentation on parallel and GPU computing with the neural network toolbox ( <a href = "http://www.mathworks.com/help/nnet/ug/neural-networks-with-parallel-and-gpu-computing.html">link here</a> ) and seen that there are a few things that can/should be done when calculating with a GPU for example converting the input and target data to GPU arrays before training with the nndata2gpu command and replacing any tansig activation functions with elliotsig which does speed up the training a bit:</p><pre class="language-matlab">%Improved GPU training
T = num2cell(sin(1:0.01:10));
net = narnet( 1:2, 10 );
[ Xs, Xsi, Asi, Ts ] = preparets( net, {}, {}, T );
rng(0)
</pre><pre class="language-matlab">net = configure(net,Xs,Ts);
Xs = nndata2gpu(Xs);
Ts = nndata2gpu(Ts);
Xsi = nndata2gpu(Xsi);
</pre><pre class="language-matlab">for i=1:net.numLayers
if strcmp(net.layers{i}.transferFcn,'tansig')
net.layers{i}.transferFcn = 'elliotsig';
end
end
</pre><pre class="language-matlab">net.trainFcn = 'trainscg';
tic
net = train(net,Xs,Ts,'showResources','yes' );
toc %70.79
</pre><p>The training here only takes about 70 seconds, but still it’s many times slower compared to just doing it on my CPU. I’ve tried several different sized data series and network architectures but I’ve never seen the GPU training being able to compete with the CPU which is strange since as I understand it most professional ANN research is done using GPU’s?</p><p>What am I doing wrong here? Clearly I must be missing something fundamental.</p><p>Thanks</p>PetterShttp://www.mathworks.com/matlabcentral/profile/authors/5894292-petterstag:www.mathworks.com,2005:Question/2258652015-06-30T08:43:33Z2015-06-30T19:15:14ZAny one please convert this C++ codes into matlab code<pre class="language-matlab">#include "naivebayes.h"
using namespace std;
</pre><pre class="language-matlab">// PUBLIC METHODS
</pre><pre class="language-matlab">/*
* Returns the created network.
*/
DSL_network* NaiveBayes::getNetwork(){
return network;
}
</pre><pre class="language-matlab">/*
* Learns the network structure base on the Naive Bayesian approach.
*/
void NaiveBayes::LearnNetwork(DSL_dataset *ds, AlgArguments *args){
network = new DSL_network();
int classifierNode = args->classifierNode;
DSL_naiveBayes naive;
bool wentWell = true;
cout << "Naive Bayes Learning Started ..." << endl;
DSL_variableInfo vi;
ds->GetVariableInfo(classifierNode,vi);
naive.classVariableId = vi.id;
if (naive.Learn(*ds,*network) == DSL_OKAY){
network->UpdateBeliefs();
std::cout << "Successfully learnt " << ds->NumVariables() << " variables using Naive Bayes, with node " << classifierNode << " as classifier." << std::endl;
}
else{
std::cout << "Learning failed for " << classifierNode << std::endl;
}
}
-------------------------
K2 Algorithm
</pre><pre class="language-matlab">#include "k2.h"
#include "algorithm.h"
using namespace std;
</pre><pre class="language-matlab">// PRIVATE METHODS
</pre><pre class="language-matlab">/*
* Creates the arcs from the parents to the current node.
* Note that the parents will always exits as this is due
* to the node ordering, which ensures that all parents are
* created before their children are.
*/
void K2::CreateArcs(int node, vector<int> *parents){
int trainNode = (*nodeOrder)[node];
string nodeID = train->GetId(trainNode);
int handle = network->AddNode(DSL_CPT, nodeID.c_str());
network->GetNode(node)->Definition()->SetNumberOfOutcomes(numStates);
for(int p =0; p < parents->size(); p++){
network->AddArc((*parents)[p], handle);
}
}
</pre><pre class="language-matlab">/*
* Creates all the possible combinations of the node
* and its parents given the number of states. These
* matricies are used to find the corrilations between
* the states of the current node compared to the
* states of its parents in the ScoreNode method. Eg:
* a node with one parent and two states would generate
* a 2D matrix containing: 0 0, 0 1, 1 0, and 1 1. This
* can be though of as counting using the number of
* states as the base number.
*/
void K2::CreateMatrices(int numStates, int maxNumParents){
com = new vector<int**>;
for(int i =0; i < maxNumParents+1; i++){
int rows = i + 1;
int cols = Power(numStates, rows);
int **d = new int* [rows];
for(int k=0; k < rows; k++){
d[k] = new int[cols];
for(int p=0; p < cols; p++){
d[k][p] = 0;
}
}
com->push_back(d);
}
vector<int> *b = new vector<int>;
for(int i = maxNumParents; i > -1; i--){
b->push_back(Power (numStates, i));
}
for(int i = 0; i < com->size(); i++){
int rows = i+1;
int cols = Power(numStates, rows);
for(int c =0; c < cols; c++){
int val =c;
for(int j = b->size()-rows; j < b->size(); j++){
int base = (*b)[j];
if(val >= base){
int cntr = 0;
while(val >= base){
val -= base;
cntr++;
}
int m = j-(b->size()-rows);
(*com)[i][m][c] = cntr;
}
}
}
}
b->clear();
}
</pre><pre class="language-matlab">/*
* Calculates the factorial of a number,
* and returns the answer.
*/
double K2::Factorial(double num){
double factorial = 1;
for(long i = 1; i < num+1; i++){
factorial *= i;
}
return factorial;
}
</pre><pre class="language-matlab">/*
* Calculates the power of a base to an exponent, and
* returns the answer.
*/
int K2::Power(int base, int exponent){
int result = 1;
for(int i =0; i < exponent; i++){
result *= base;
}
return result;
}
</pre><pre class="language-matlab">/*
* Removes all instances of the "nodeToRemove" node from the vector "parents".
*/
void K2::RemoveNodeFromParents(int nodeToRemove, vector<int> **parents){
vector<int> *temp = new vector<int>;
for(int i =0; i < (*parents)->size(); i++){
if((**parents)[i] != nodeToRemove){
temp->push_back((**parents)[i]);
}
}
(*parents)->clear();
*parents = temp;
}
</pre><pre class="language-matlab">/*
* This is the implementation of the scoring function proposed by Cooper and Herskovits.
* The function works in by comparing the current node and its parents to a 2D array
* (implemented as com). However note the adaption of the alpha value from representing
* a count in the origional, to representing a percentage in this implementation. This
* was due to the calculation of the factorial of alpha, which is dependant on the
* training set size. When the training set grows above around 100 elements, then its
* factorial can't be reliably calculated. So the count is rather represented a
* percentage of the total training size. Note that the node is also parameterized as
* including this step now reduced construction time significantly.
*/
double K2::ScoreNode(int node, vector<int> *parents, DSL_Dmatrix **dm){
// Sort the parents into accending order first
sort(parents->begin(), parents->end());
int rows = parents->size() + 1;
int cols = Power(numStates, rows);
vector<int> Alpha_ijk;
vector<double> params;
vector<double> d;
vector<int> N_ij;
// Observe at least 1 occourance which therefore prevents the probabiity of
// an unobserved state being zero.
Alpha_ijk.resize(cols, 1);
params.resize(cols, 1);
N_ij.resize(cols/numStates);
d.resize(cols/numStates);
int trainNode = (*nodeOrder)[node];
vector<DSL_dataElement> nodeData = train->GetVariableData(trainNode);
</pre><pre> DSL_intArray dim;
for(int y=0; y < rows; y++){
dim.Add(numStates);
}
*dm = new DSL_Dmatrix(dim);</pre><pre> int trainSize = train->NumRecords();
for(int d =0; d < trainSize; d++){
for(int c =0; c < cols; c++){
int inParents = 0;
for(int r = 0; r < parents->size(); r++){
int parentValue = (*com)[parents->size()][r][c];
int trainParent = (*parents)[r];
vector<DSL_dataElement> parentData = train->GetVariableData(trainParent);
if(parentValue == parentData[d].i){
inParents++;
}
}
int nodeValue = (*com)[parents->size()][rows-1][c];
bool found = false;
if(nodeValue == nodeData[d].i){
found = true;
}
if(found == true && inParents == parents->size()){
Alpha_ijk[c]++;
params[c]++;
}
}
}
for(int i =0; i < N_ij.size(); i++){
int start = i * numStates;
int end = start + numStates;
for(int j = start ; j < end; j++){
// Alpha represented as a percentage
Alpha_ijk[j] = (double)Alpha_ijk[j]/(double)trainSize*100;
N_ij[i] += Alpha_ijk[j];
d[i] += params[j];
}
}
// Parametrizing the node with its potential parents
for(int m =0; m < params.size(); m++){
int k = m/numStates;
if (d[k] == 0) {
params[m] = 1/(float)numStates;
}
else{
params[m] = params[m]/(double)d[k];
}
(**dm)[m] = params[m];
}</pre><pre> // Calculating the score
double numerator = Factorial(numStates-1);
double score = 1;
for(int i =0; i < N_ij.size(); i++){
double denominator = Factorial(N_ij[i] + numStates -1);
if(denominator == 0) denominator = 1;
double fraction = numerator/denominator;
double factorial = 1;
int start = i * numStates;
int end = start + numStates;
for(int j = start ; j < end; j++){
factorial *= Factorial(Alpha_ijk[j]);
}
score *= fraction * factorial;
}
return score;
}</pre><pre class="language-matlab">// PUBLIC METHODS
</pre><pre class="language-matlab">/*
* Returns the created network.
*/
DSL_network* K2::GetNetwork(){
network->UpdateBeliefs();
return network;
}
</pre><pre class="language-matlab">/*
* This is the implementation of the K2 algorithm proposed by Cooper and Herskovits.
* The scoring fuction is implemented in the ScoreNode method. Note that we have
* included the parameterization step in the ScoreNode function aswell, as this
* was found to reduce construction time.
*/
void K2::LearnNetwork(DSL_dataset *train, AlgArguments *args){
// Creating the node order, which is currently the order in the training dataset.
for(int i = 0; i < nodeOrder->size();i++){
(*nodeOrder)[i] = i;
}
numStates = args->numStates;
double networkScore = 1;
int maxNumParents = args->maxNumParents;
CreateMatrices(numStates, maxNumParents);
// The implementation of the K2 algorithm
for(int i = 0 ; i < maxNumNodes; i++){
vector<int> * parents = new vector<int>;
DSL_Dmatrix *bestDM = NULL;
DSL_Dmatrix *oldBestDM = new DSL_Dmatrix;
double oldScore = ScoreNode(i, parents, &bestDM);
bool OkToProceed = true;
double maxScore = -1;
while( OkToProceed && parents->size() < maxNumParents && i > 0){
int bestNode = -1;
*oldBestDM = *bestDM;
bestDM == NULL;
for(int k = 0; k < i; k++){
// A check if the potential parent is already a parent.
bool alreadyAParent = false;
for(int p =0; p < parents->size(); p++){
if( k == (*parents)[p]){
alreadyAParent = true;
}
}
if(alreadyAParent == false){
parents->push_back(k);
DSL_Dmatrix *dm = NULL;
double newScore = ScoreNode(i, parents, &dm);
if(newScore > maxScore){
maxScore = newScore;
bestNode = k;
*bestDM = *dm;
}
dm->CleanUp();
RemoveNodeFromParents(k, &parents);
}
}
// If a parent node was found to maximize the score of the current node
// then it becomes a parent of the current node, else if no parent was
// found to maximize the score, then move to calculate the score of the
// next node. Note, that there is also a limit on the maximum number of
// parents, which is found in the parameters of the while loop.
if(maxScore > oldScore){
oldScore = maxScore;
parents->push_back(bestNode);
}
else{
OkToProceed = false;
*bestDM = *oldBestDM;
}
}
CreateArcs(i, parents);
network->GetNode(i)->Definition()->SetDefinition(*bestDM);
networkScore *= oldScore;
cout << "Final score for node " << i+1 << " was = " << oldScore << " ";
cout << "Final num Parents : " << parents->size() << ", with nodes: ";
for(int m =0; m < parents->size();m++){
cout << (*parents)[m]+1 << " ";
}
cout << endl;
}
cout << "Final network score of " << networkScore << ", number of parents = " << maxNumParents << endl;
}
-----------------------
greedy thick thinning
</pre><pre class="language-matlab">#include "greedythickthinning.h"
using namespace std;
</pre><pre class="language-matlab">/*
* The default implementation of the Greedy Think Thinning algorithm.
*/
void GreedyThickThinning::LearnNetwork(DSL_dataset *train, AlgArguments *args){
network = new DSL_network;
DSL_greedyThickThinning gtt;
gtt.maxParents = args->maxNumParents;
int msg = gtt.Learn(*(train),*network);
if(msg == DSL_OKAY){
network->UpdateBeliefs();
cout << "Successfully learnt a network using the GreedyThickThinning algorithm" << endl;
}
else{
cout << "Error: There was an error with learning the network using the GreedyThickThinning algorithm" << endl;
}
}
</pre><pre class="language-matlab">DSL_network* GreedyThickThinning::GetNetwork(){
return network;
}
</pre>Indhttp://www.mathworks.com/matlabcentral/profile/authors/1955677-indtag:www.mathworks.com,2005:Question/2258682015-06-30T09:00:04Z2015-06-30T19:06:36ZHow many matlab licenses can be used on the same workstation?<p>Hi,
we have an HPC system, which has two GPUs. Currently there is only a profile who is enabled for using MATLAB (ver. 2014a), but we need to create a new one for another user. We bought a new license for MATLAB 2014b, therefore our IT specialist would like to know if we can install the 2014b version on the same machine and if the two versions can generate problems.
Regards
Giovanni</p>Giovanni Marinohttp://www.mathworks.com/matlabcentral/profile/authors/3892693-giovanni-marinotag:www.mathworks.com,2005:Question/2259602015-06-30T19:01:44Z2015-06-30T19:02:23ZProtected Simulink model to previous versions.<p>Is there any way to get a Simulink model protected and saved to a previous version? I had previously exported it as a protected model from a model that had been saved in a previous version. But it seems that the process of exporting to a protected model saves it in the current version.</p>Michael Schultehttp://www.mathworks.com/matlabcentral/profile/authors/6651914-michael-schultetag:www.mathworks.com,2005:Question/2254882015-06-26T15:24:46Z2015-06-30T18:58:22ZHow can I "black box" a Simulink Model?<p>I have created a Simulink model that I need to send to a customer. The Simulink model contains proprietary information so I would like to create a custom "block" so that the methods and values cannot be seen. Masking the routine does not work in this case because the model can still be accessed. I was thinking that a .mex file would be the way to go but I haven't found a way to convert a model to ".mex".
Any tips would be appreciated.</p>Michael Schultehttp://www.mathworks.com/matlabcentral/profile/authors/6651914-michael-schultetag:www.mathworks.com,2005:Question/2259522015-06-30T17:46:40Z2015-06-30T18:54:55ZUsing c-files in Matlab<p>I would like to use a c-program in Matlab. It consists of several c-files. I have read several approaches, and also most of the examples I see is to write the c-code in a mex wrapper and compile it. What I want is to include these c-files in the mex file, and compile and link it. I also read about compiling them separately with a c-compiler and load the library. Does anyone have a clear set of instructions or directions on what would be the best way to go about this? Thanks a lot!</p>Jasonhttp://www.mathworks.com/matlabcentral/profile/authors/2619951-jasontag:www.mathworks.com,2005:Question/2257362015-06-29T09:54:08Z2015-06-30T18:52:52ZHow to hide image inside another image as well as extract it from the image using LSB?<p>How to hide image inside another image as well as extract it from the image using LSB in matlab?</p>Anushkahttp://www.mathworks.com/matlabcentral/profile/authors/6068164-anushkatag:www.mathworks.com,2005:Question/2258842015-06-30T10:16:37Z2015-06-30T18:52:44ZHow to get RGB-values out of video frames using VideoReader-function. When reading an individual frame using impixel-function I get only 3 times zero for RGB.<pre> videoObject = VideoReader('TypeI_4_1_TestClipped.wmv');
imageData = read(videoObject);</pre><pre> numFrames = get(videoObject, 'NumberOfFrames');
Heig= get(videoObject, 'Height');
Wid= get(videoObject, 'Width');
Rateframe= get(videoObject, 'FrameRate');
time=get(videoObject, 'Duration');</pre><pre> % To cut down the time for this trial height and width are reduced
Wid=200;
Heig=100;
Hii = Heig*(ones(1,Wid));</pre><pre> mov(10).cdata = read(videoObject,10);
P1=impixel(mov(10).cdata,wii,Hii);</pre><pre> % or</pre><pre> imagedata=read(videoObject,10);
P2=impixel(mov(10).cdata,wii,Hii);</pre><pre> % Both P1 and P2 appear to became 200 x 3 full of zeros</pre>Pekka Koivistohttp://www.mathworks.com/matlabcentral/profile/authors/4040596-pekka-koivistotag:www.mathworks.com,2005:Question/2252502015-06-25T08:26:14Z2015-06-30T18:48:25ZHow to draw a ROI (rectangle) in an image and get the coordinates<p>Hi</p><p>I am trying to draw a rectangle in an image and get the coordinates in order to match them with the XYZ values. I tried some of the code I found here, along with some changes to implement that to my case, but I don't think it works well!</p><pre class="language-matlab">%Draw a ROI = rectangle
message = sprintf('Draw a box over the image.\nDouble click inside the box to finish drawing.');
uiwait(msgbox(message));
%%
rect=imrect;
binaryImage = rect.createMask();
xy = rect.getPosition;
</pre><pre class="language-matlab">% Calculate the area, in pixels, that they drew.
numberOfPixels1 = sum(binaryImage(:))
</pre><pre class="language-matlab">%get the coordinates.. this is for freehand -> what do I have to change???
structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.
subplot(2, 3, 1); % Plot over original image.
hold on; % Don't blow away the image.
plot(x, y, 'LineWidth', 2);
</pre><pre> drawnow; % Force it to draw immediately.</pre><pre class="language-matlab">%match the coordinates (positions)with the XYZ values
for i=1:length(x)
X(i)=XYZ2(y(i),x(i),1);
Y(i)=XYZ2(y(i),x(i),2);
Z(i)=XYZ2(y(i),x(i),3);
end
</pre><p>Any ideas? Also, is it possible to use this specific ROI to a raw of images?</p><p>Many thanks</p>Johttp://www.mathworks.com/matlabcentral/profile/authors/5497563-jotag:www.mathworks.com,2005:Question/2258852015-06-30T10:22:39Z2015-06-30T18:48:19Zgenerating c++ code from matlab<p>i want to generate c++ code from matlab , how can i do this.I searched in google i got information about matlab coder , can u please tell me how to install and configure matlab coder</p>RENUKA MUCCHERLAhttp://www.mathworks.com/matlabcentral/profile/authors/6659309-renuka-muccherlatag:www.mathworks.com,2005:Question/2259332015-06-30T15:44:06Z2015-06-30T18:45:25Z'Problem' with fzero<p>Hi, hope you all are well. I am here due to a problem with the function called 'fzero'.</p><p>On one hand, I have this file: <i>f.m</i></p><pre class="language-matlab">function y=f(x)
y= besselj(1,x);
</pre><p>And on the other hand: <i>exercise.m</i></p><pre class="language-matlab">D=fzero(@f,[0 10]);
tam=length(D);
for i=1:tam
fprintf(' Possible MAX or MIN: f(%f) \n',D(i))
end
</pre><p>When I run exercise.m, I get this output:</p><pre> Possible MAX or MIN: f(0.000000) </pre><p>I know where this values should be located...</p><img src = "/matlabcentral/answers/uploaded_files/33460/Captura%20de%20pantalla%202015-06-30%20a%20las%2017.39.17.png"><p>What am I doing wrong?
Thanks in advance.
PD: I have to use fzero and besselj(1,x) at [0:10]</p>JMhttp://www.mathworks.com/matlabcentral/profile/authors/3847838-jmtag:www.mathworks.com,2005:Question/2259202015-06-30T13:57:39Z2015-06-30T18:31:22ZDouble vs. Cell "Undefined function 'plus' for input arguments of type 'cell' "<p>In my code, I have two variables (inp.W{9} & inp.W{10}) which seems to be double (when I remove semicolon, this is shown in command Window: ans = [1x10 double]). However when I try to add these two variables, I get this error:</p><p>Undefined function 'plus' for input arguments of type 'cell'.</p><p>Error in truck (line 21)
inp.W{9}+inp.W{10}</p>Sam136http://www.mathworks.com/matlabcentral/profile/authors/5511365-sam136tag:www.mathworks.com,2005:Question/2258982015-06-30T11:39:22Z2015-06-30T18:28:20ZHow to determine the number of correct frames, missed frames and false frames in a video?<p>Hello Sir,
I have a sample project where an object is being detected and tracked in a video using optical flow method. I would like to find how many frames are being detected correctly, and how many frames are missed and how many frames are false</p>Nitesh Sanklechahttp://www.mathworks.com/matlabcentral/profile/authors/2484695-nitesh-sanklechatag:www.mathworks.com,2005:Question/2258952015-06-30T11:20:51Z2015-06-30T18:27:33ZRGB values in a YUV colorspace image<p>I have an image in YUV colorspace and when i preview it using imshow() function,the image shows RGB values at each pixel but when i type img_name(x,y,:) in the workspace,it shows some other values.
So how do i get those RGB values which are shown in the figure using the imshow() function in the workspace or use them for further processing.</p>nitinhttp://www.mathworks.com/matlabcentral/profile/authors/6349718-nitintag:www.mathworks.com,2005:Question/2254572015-06-26T11:48:07Z2015-06-30T18:26:54ZFitting of parameters of function with discrete / integer argument<p>Could somebody help me find the proper way to find the parameters for a function with integer arguments?
I've conducted a series of measurement:</p><pre class="language-matlab">p_1 , p_2 , p_3 , (p_1+p_2)/2 , (p_2+p_3)/2 , (p_1+p_3)/2, (p_1+p_2+p_3)/3 , ....
</pre><p>(and so on, up to 10 parameters).
Each measurement has its own measurement error and I would like to find the proper way to find parameters <tt>p_1</tt> , <tt>p_2</tt> , <tt>p_3</tt>, with standard deviation...</p><p>Thanks in advance!</p>Selwynhttp://www.mathworks.com/matlabcentral/profile/authors/3017421-selwyntag:www.mathworks.com,2005:Question/2256752015-06-28T20:28:35Z2015-06-30T18:24:35ZHow can I create a 3d plot with each vector displayed as an arrow, and one line connecting the tail to tip?<p>I am trying to create a program that can import an excel file of 3 columns with the vector data, and display these vectors into a 3d graph. Here's my code so far. I am only getting an empty graph generated though :/</p><pre class="language-matlab">data = xlsread('vectordata.xlsx');
radius = data(:,1);
theta = data(:,2);
phi = data(:,3);
x = radius.*cos(theta).*sin(phi);
y = radius.*sin(theta).*sin(phi);
z = radius.*cos(phi);
sumx = sum(x(:));
sumy = sum(y(:));
sumz = sum(z(:));
</pre><pre class="language-matlab">[radius, theta, phi] = cart2sph(sumx, sumy, sumz);
</pre><pre class="language-matlab">xpt(1) = 0;
ypt(1) = 0;
zpt(1) = 0;
pt(1,1) = xpt;
pt(1,2) = ypt;
pt(1,3) = zpt;
</pre><pre class="language-matlab">numvec = size(data,1);
</pre><pre class="language-matlab">for k = 1:numvec;
xpt1 = 1:numvec;
ypt1 = 1:numvec;
zpt1 = 1:numvec;
end
</pre><pre class="language-matlab">figure
plot3(radius, theta, phi);
axis([0 5 0 5 0 5]);
xlabel('x forces');
ylabel('y forces');
zlabel('z forces');
title('3D vector graph');
</pre><p>thanks in advance.</p>John Perrowhttp://www.mathworks.com/matlabcentral/profile/authors/6585970-john-perrowtag:www.mathworks.com,2005:Question/2258092015-06-29T19:20:42Z2015-06-30T18:24:04ZDo I need to use specific 'PCI to serial port card' presented on your web site for my xpc target computer?<p>I built my simulink model for RS-232 communication with external PC using FIFO blocks.
But, when I read the help document and tried several ways, it looks like separate ports are needed for each of sending and receiving data. Using both sending and receiving blocks at the same time with port 1 showed me an error. Is it correct to use different com ports for sending and receiving data?</p><p>Now, I am trying to add extra com port using "PCI to RS-232 card". In this case, do I need to use the hardware presented on your web site? If so, can you give the direction about how to install drivers for my device on xpc target?</p><p>Thanks.</p>Kyunggeune Ohhttp://www.mathworks.com/matlabcentral/profile/authors/6657863-kyunggeune-ohtag:www.mathworks.com,2005:Question/2256772015-06-28T21:26:09Z2015-06-30T18:21:46ZALSA lib pcm Error<p>I am having trouble playing sound with MATLAB R2015a on Linux/XUbuntu 15.04.
When executing</p><pre class="language-matlab">load handel;
sound(y,Fs);
</pre><p>for instance, the terminal throws the errors shown in the attachement. A colleague of mine is facing the same issues on an XUbuntu machine.</p><p>I use an external class complient USB sound interface (Lexicon Alpha) which is the system's default sound device.</p><p>What to do?</p>Jenshttp://www.mathworks.com/matlabcentral/profile/authors/4409795-jenstag:www.mathworks.com,2005:Question/2259582015-06-30T18:20:14Z2015-06-30T18:21:47ZHow do I send a wireless UDP signal to an Arduino running a Simulink program?<p>I want to send a number 0-255 to an Arduino Uno to be as a duty cycle for a PWM signal. I have a Simulink program that successfully receives a wired signal and makes a PWM signal, but I have trouble when moving to wireless.</p><p>Here are the details:
I have an Arduino Uno with a Dragino Yun WiFi shield on it. The shield is all set up and is connected to the same WiFi my computer is on. The Arduino is running a Simulink program that simply receives a duty cycle, and sends out a PWM signal based on it. If no duty cycle is available, it waits uses the previous duty cycle it saw (or 0 if none has been sent yet). The block I use to receive is the Arduino WiFi UDP Receive set to port 50001.</p><p>This is where I run into trouble. I am a beginner with Matlab wireless connections. Here's an example of the code I tried for sending a number to the Arduino:</p><p>>> u=udp('192.168.1.101', 50001);%IP address of the Dragino Yun shield given by the Arduino IDE</p><p>>> fopen(u);</p><p>>> fwrite(u,50);</p><p>>> fclose(u);</p><p>I have tried other variations of the upd function but I do not understand it very well. Is there anyone who knows what the Matlab code should look like?</p><p>Thank you!</p>Timothy Castigliahttp://www.mathworks.com/matlabcentral/profile/authors/5591918-timothy-castigliatag:www.mathworks.com,2005:Question/2250142015-06-23T19:10:38Z2015-06-30T18:16:56ZWaitbar message disappears and can't be updated (GUI)<p>I am working on a GUI which analyzes data using quite lengthy calculations. I am trying to implement waitbars to show the progression of serveral different processes that the GUI performs. However, in the case of one of those processes, my waitbar progresses, but the message just above it disappears when I first update the bar. If I try to include the message in subsequent waitbar calls (waitbar(x,h,'updated message')), Matlab returns an error ('Improper arguments for waitbar').</p><p>I won't include code here since the calls to this waitbar span several functions. In brief, I first call and create the waitbar in a callback function of my main interface m file (it activates after the user presses on a button which triggers a calculation). Afterwards, I update the waitbar in several 'for loops' contained in seperate functions that the callback function inside the main interface calls. I made the handle of the waitbar global so I could call it inside my different functions, and I specify the handle every time I update the waitbar. The message still does not display after the first call, though.</p><p>What could be causing this? Is it possible to use a waitbar to monitor the progress of a process that spans several functions?</p>Rosalie Martelhttp://www.mathworks.com/matlabcentral/profile/authors/6152723-rosalie-marteltag:www.mathworks.com,2005:Question/2258712015-06-30T09:24:58Z2015-06-30T18:11:55ZI cannot use deployment Tool in my matlab 2015 because when I select Application Compiler, I get this figure window.What to do now? Regards<p>When I type deploytool in command window and press enter,a window appears showing 4 options.When I select the 1st ie application compiler, I get another window which says could not save project file in the specified folder.You may have not write permission.Now what to do?</p>Sadiq Akbarhttp://www.mathworks.com/matlabcentral/profile/authors/966774-sadiq-akbar