https://fr.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2017-04-27T18:36:46Ztag:fr.mathworks.com,2005:Question/849782013-08-17T11:51:14Z2017-04-27T18:36:46ZTwo NIFTI Images Registration<p>Hi all.</p><p>I have two NIFTI images and I need to register them in a single one.
I think that collapse_nii_scan from this toolbox <a href = "http://www.mathworks.com/matlabcentral/fileexchange/8797-tools-for-nifti-and-analyze-image">http://www.mathworks.com/matlabcentral/fileexchange/8797-tools-for-nifti-and-analyze-image</a> might help, but I can't get what I was expecting.</p><p>Can anyone explain me how should I do it or show me another way?</p><p>Thanks in advance</p><p>Gustavo</p>Gustavohttps://fr.mathworks.com/matlabcentral/profile/authors/4387240-gustavotag:fr.mathworks.com,2005:Question/3376692017-04-27T16:24:13Z2017-04-27T18:35:53Zwhen calling the function NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC); and using the "figure" command, no graph displays, only a grayed-out background on the figure window. I don't understand what the problem could be?<p>when calling the function</p><pre class="language-matlab">NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
</pre><p>and using the "figure" command, no graph displays, only a grayed-out background on the figure window. I don't understand what the problem could be? My professor said that all of the functions were defined correctly and they were all imported correctly, as well. The NBERbcYY function creates recession bars in the graph, the y variable is the Mcoppock curve(a causal fir filter)that was created by my professor.</p><p>Here are the two functions I am using:</p><pre class="language-matlab">function [ah, fh1, fh2] = NBERbcYY(time, y1, y2, LS, LW, LC)
LS = {'-'; '--'; ':'};
LW = [2 1 2];
LC = {'b'; 'm'; 'r'};
</pre><pre class="language-matlab">function y=mcoppock(x)
b=[3 2 2 1 1 1 0 0 0 0 0 0 -3 -2 -2 -1 -1 -1];
a=12;
</pre><pre class="language-matlab">y=filter(b,a,x);
</pre><p>here is the script I used to try and create the graph:</p><pre class="language-matlab">time=[1980+1/12:1/12:2017+3/12];
y=mcoppock(UNRATE);
NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
</pre><pre class="language-matlab">Cannot find an exact (case-sensitive) match for 'LS'
</pre><pre class="language-matlab">The closest match is: ls in C:\Program Files\MATLAB\R2017a\toolbox\matlab\general\ls.m
</pre><pre class="language-matlab">Did you mean:
</pre><pre class="language-matlab">>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)LS,LW,LC);
NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)LS,LW,LC);
↑
Error: Unexpected MATLAB expression.
</pre><pre class="language-matlab">Did you mean:
>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)*ls,LW,clc);LS = {'-'; '--'; ':'};
LW = [2 1 2];
LC = {'b'; 'm'; 'r'};
Error using *
Inner matrix dimensions must agree.
</pre><pre class="language-matlab">>> LS = {'-'; '--'; ':'};
LW = [2 1 2];
LC = {'b'; 'm'; 'r'};
>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)LS,LW,LC);
NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)LS,LW,LC);
↑
Error: Unexpected MATLAB expression.
</pre><pre class="language-matlab">Did you mean:
>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
>> figure
>> LS = {'-'; '--'; ':'};
LW = [2 1 2];
LC = {'b'; 'm'; 'r'};
>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
>> LS = {'-'; '--'; ':'};
LW = [2 1 2];
LC = {'b'; 'm'; 'r'};
>> figure
Warning: MATLAB has disabled some advanced graphics rendering features by switching to software OpenGL. For more
information, click here.
>> figure,
>> NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
>> end
end
↑
Error: Illegal use of reserved keyword "end".
</pre><pre class="language-matlab">>> figure, NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)LS,LW,LC);
figure, NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)LS,LW,LC);
↑
Error: Unexpected MATLAB expression.
</pre><pre class="language-matlab">Did you mean:
>> figure, NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1)*LS,LW,LC);
Undefined operator '*' for input arguments of type 'cell'.
</pre><pre class="language-matlab">>> figure,NBERbcYY(time(1,20:447),y(20:447,1),UNRATE(20:447,1),LS,LW,LC);
</pre><p>as you can see, I tried several things, even pasting the variable assignment for LS,LW,LC which I shouldn't have to, given that they are already included in the function definition. If anybody has any suggestions that might help me resolve this issue, I would greatly appreciate your input. Thanks in advance.</p>Scott Rachelsonhttps://fr.mathworks.com/matlabcentral/profile/authors/10226732-scott-rachelsontag:fr.mathworks.com,2005:Question/3374672017-04-26T17:50:57Z2017-04-27T18:35:24ZHow to find a constrained distribution within an array that results in an optimum.<p>Hi,</p><p>This is my first time posting here so please bear with me. I have been struggling with an optimization problem for a while now and was hoping somebody here might have a solution or can steer me in the right direction.</p><p>I have a function: y = a * b * c * x.
a, b, c are arrays of 20 elements which are constants and I am trying to optimize y. The problem now lies with x.</p><p>x is also an array with 20 elements, however each value can take a value ranging from 0 to a certain maximum value. The problem now is, is that the array x summed up has to be a certain value. I am thus trying to optimize y for a certain distribution of values over the array x, while the summed value stays the same.</p><p>x is also an array with 20 elements, however each value can take a value ranging from 0 to a certain maximum value. The problem now is, is that the array x summed up has to be a certain value. I am thus trying to optimize y for a certain distribution of values over the array x, while the summed value stays the same.</p><p>I hope my explanation is clear enough and if you have any questions please let me know.</p><p>Any help would be greatly appreciated.</p>Jordy van der Polhttps://fr.mathworks.com/matlabcentral/profile/authors/8283146-jordy-van-der-poltag:fr.mathworks.com,2005:Question/3373282017-04-26T04:39:32Z2017-04-27T18:33:53ZHow to get all the coefficients of a polynomial?<p>I tried the sample from MATLAB documentation but I get something else which is different from the result in the documentation. Does anyone know where I did it wrong?
The result in the documentation is be [3,0,0] which returns all the coefficients all the way from 0 degree. But I get 3*x^2 which makes no sense.</p><img src = "/matlabcentral/answers/uploaded_files/76194/coeffQ.JPG">DmArcherhttps://fr.mathworks.com/matlabcentral/profile/authors/8393199-dmarchertag:fr.mathworks.com,2005:Question/3375132017-04-26T23:03:12Z2017-04-27T18:33:41ZHow to plot using the mod function?<p>I'm trying to plot an energy graph, and I'm having trouble plotting both the mod function. I don't understand why I cannot plot each point when mod(t,etime) == 0 and mod(t,ptime) == 0. The mod(t,etime) == 0 function only plots at the end, and I would like it to plot continuously. Could someone please help me figure this out?</p><pre> function MDSim(T,sigma,m,dt,rc,L,k,ptime,etime)
tempcontrol=input('Would you like Temperature Control? [Y/N] \n','s');
while (tempcontrol ~= 'n' && tempcontrol ~= 'y')
tempcontrol=input('Would you like Temperature Control? [Y/N] \n', 's');
end</pre><pre> [xpos,ypos,vx,vy]=Initialize(sigma,L,k);</pre><pre> h=cell(8);</pre><pre> for i=1:64
h{i}=rectangle('Position',[xpos(i)-0.5*sigma ypos(i)-0.5*sigma sigma sigma],'Curvature',[1 1], 'FaceColor','b');
axis equal
end</pre><pre> t=0;
while T > t
t=t+1;
[xpos,ypos,vx,vy,U_tot,K_avg_tot,E_tot]=Step(xpos,ypos,vx,vy,dt,m,L,sigma,rc,k,tempcontrol);
if mod(t,ptime) == 0
for j=1:64
figure(1);
set(h{j},'Position',[xpos(j)-0.5*sigma ypos(j)-0.5*sigma sigma sigma])
axis equal
end
hold on
drawnow
hold off
end
if mod(t,etime) == 0</pre><pre> %disp(['Total Energy is: ', num2str(E_tot)])
figure(2);
plot(t,(U_tot),'rd', t,(K_avg_tot),'b+',t,(E_tot),'m*')</pre><pre> title('Total Energy (E), Potential Energy (U),Kinetic Energy (K) vs. Time (s)');
xlabel('Time (ds)');
ylabel('Energy (J)');
legend('E','U', 'K', 'Location', 'EastOutside');</pre><pre> hold on
drawnow()</pre><pre> hold off
end</pre><pre> end
end
% </pre>Akhil Vasvanihttps://fr.mathworks.com/matlabcentral/profile/authors/7894695-akhil-vasvanitag:fr.mathworks.com,2005:Question/3359682017-04-18T16:12:36Z2017-04-27T18:32:55ZHow to fix this error 'Error using xor Matrix dimensions must agree'?<p>Here is my code</p>wafflehttps://fr.mathworks.com/matlabcentral/profile/authors/9170912-waffletag:fr.mathworks.com,2005:Question/3376912017-04-27T18:32:02Z2017-04-27T18:32:02ZHow to save variables as 16-bit signed integers?<p>Hi! I have a <i>dct_blk</i> array and I need to save it as a 16-bit signed integers. I did the following:</p><pre> A = dct_blk';
fileID = fopen('img03y.dq','w');
fwrite(fileID,A,'integer*2');
fclose(fileID);</pre><p>I transponse <i>dct_blk</i> because I need to store it in raster order from left-to-right and moving from top-to-bottom. But when I read my saved binary with the following code</p><pre> fileID = fopen('img03y.dq');
B = fread(fileID,[N M],'uint16');
B = B';</pre><p>I'm not getting the same values as <i>dct_blk</i>. I'm getting large numbers where the negative values supposed to be. What can I be doing wrong? Any help will be greatly appreciated.</p><p>Thank you.</p>Agustinhttps://fr.mathworks.com/matlabcentral/profile/authors/5558144-agustintag:fr.mathworks.com,2005:Question/3376902017-04-27T18:29:10Z2017-04-27T18:31:24ZUsing sprintf (problem with integer)<p>Hi to everybody,
I have got a problem using sprintf. I'm using it for doing the following operation:</p><pre> step_value=sprintf('step%d',steps(i)*100);</pre><p>..where "steps" is a simple array containing numbers with two decimals.
The problem is that at i=9 I get:</p><p>steps(9)*100</p><p>ans =
55.0000</p><p>sprintf('%d',ans)</p><p>ans=
5.500000e+01</p><p>...which is not clearly in integer notation. I don't have problems for the other i-elements, just for i=9.</p><p>Someone knows what is it the problem?
Thanks :)</p>Andrea Bracchittahttps://fr.mathworks.com/matlabcentral/profile/authors/5288768-andrea-bracchittatag:fr.mathworks.com,2005:Question/3374772017-04-26T19:42:44Z2017-04-27T18:26:44ZHow can I create a cell array whose cells are strings based on a sequence of integers 1:N (for any N)?<p>I want my function to add a legend to a plot where the legend has a variable number of items depending on N: e.g. '1', '2', '3' if N=3. The help file tells me I can use a matrix or a cell array: legend(M). But I can't find a way of creating a suitable array without fixing the number of cells. For example,</p><pre class="language-matlab">num2cell(1:N)'
</pre><p>doesn't help because legend() only seems to accept cell arrays containing strings, not numeric values. And int2str() doesn't help because it adds spaces in between the numbers.</p>Richard Guntonhttps://fr.mathworks.com/matlabcentral/profile/authors/9842073-richard-guntontag:fr.mathworks.com,2005:Question/736392013-04-26T05:12:10Z2017-04-27T18:24:46Zsending and receiving IMAGE using serial port(USB to serial)<p>Hi friends,</p><p>Actually I have an image which need to be transferred via serial port. As my laptop dosent contain serial port i am using USB to serial convertor.I am sending image from one computer other using two USB to serials and null modem. I am doing this for testing purpose and later null modem will be replaced by 8051 controller. I wrote a code for transferring but i am unable to receive data proper control. Please check the below code.</p><p><b>For Transfering</b></p><pre class="language-matlab">if true
</pre><pre> SendData=serial('COM1','BaudRate',256000);
fopen(SendData);
[rows,columns]=size(Encryptedimage);
for k=1:3
for i=1:rows
for j=1:columns
data=num2str(EncryptedImage(i,j,k));
fprintf(SendData, '%c' , '*');
fprintf(SendData, '%s',data);
end
end
end
fclose(SendData);
delete(SendData);
clear SendData;</pre><pre class="language-matlab">end
</pre><p><b>For receiving</b></p><pre class="language-matlab">if true
</pre><pre class="language-matlab">recData=serial('COM2','BaudRate',256000);
fopen(recData);
while(1)
Input1=fread(receiveTemp)
</pre><pre> if(isempty(Input1))
continue;
else
disp('Value received')
for k=1:3
for i=1:rows
for j=1:columns</pre><pre> Input1=char(Input1);
Input1=sscanf(Input1, '%d');
EncryptedImage1(i,j,k)=Input1;
Input1=fread(receiveTemp);</pre><pre> end
end
end
end
if(i==rows & j==columns & k==3)
break;
end
end</pre><pre class="language-matlab">end
</pre><p>Now problem is while receiving Input1 is getting around 120 values at a time.
please help me in rectifying this issue.</p>srikanthhttps://fr.mathworks.com/matlabcentral/profile/authors/3816884-srikanthtag:fr.mathworks.com,2005:Question/3373882017-04-26T10:38:42Z2017-04-27T18:23:29ZHow to calculate euclidean distance to a loaded dataset.?<p>Sir,
I have the data of 401*22double and we have to find the euclidean distance for that dataset.my dataset consists of 401 images with 22 features using pdist2 function.</p>NAVEEN KUMARhttps://fr.mathworks.com/matlabcentral/profile/authors/10082372-naveen-kumartag:fr.mathworks.com,2005:Question/3366752017-04-22T13:01:01Z2017-04-27T18:21:38ZHow to model the gap between piston and cylinder?<p>Hi,</p><p>I'm modelling a piston in Simscape which is moving inside a cylinder. I would like to measure the flow through the gap between the piston and the cylinder wall (Even if the gap is very small) when the piston is moving til the bottom of the cylinder.</p><p>Until now I haven't found any hydraulic cylinder which is able to simulate the gap. Now I'm wondering how to do that. Can anyone help me?</p><p>I would be very thankful for any help or hint!
Greetings, kathy</p>smaruhttps://fr.mathworks.com/matlabcentral/profile/authors/2308022-smarutag:fr.mathworks.com,2005:Question/3376592017-04-27T15:16:04Z2017-04-27T18:20:57ZSeries Summation With Function Handles<p>I am performing a Monte Caro simulation with non-linear optimization inside using fmincon. Fmincon requires the use of function handles. However, I want to perform a series summation, as attempted when defining Elife with symsum. Since symsum only takes symbolic variables, how would I perform this summation using function handles? To simplify the code, everything before the for loop is just setting up the distributions and inside the for loop is where I define a couple functions and where I set up and perform the optimization.</p><pre class="language-matlab">clear all
m_tlife = 33;
std_tlife = 11;
dist_tlife = makedist('Normal', m_tlife, std_tlife);
a_drate = 2;
b_drate = 0.006;
dist_drate = makedist('Gamma', a_drate, b_drate);
m_Ee = 4.56;
std_Ee = 0.27;
dist_Ee = makedist('Normal', m_Ee, std_Ee);
m = 34;
Asp = 40.1; % m^2
em = 0.162;
Np = 10;
for i = 1:Np
tlife = random(dist_tlife);
sigma = random(dist_drate);
Ee = random(dist_Ee);
Ep = Asp*em*Ee*365/m;
Elife = @(x)symsum(Ep*(m - x(2))*(1 - sigma)^x(1) + Ep*x(2)*(1 - sigma)^(tlife - x(1)), x(1), 1, tlife);
fun = @(x)Elife(x)*x(2)/(1 + x(1))
x0 = [0,0];
lb = [0,0];
up = [tlife m];
A = [];
b = [];
Aeq = [];
beq = [];
x(i,:) = fmincon(fun, x0, A, b, Aeq, beq, lb, up);
L(i) = fun(x)*10^2;
end
</pre>Andrew Poissanthttps://fr.mathworks.com/matlabcentral/profile/authors/4445510-andrew-poissanttag:fr.mathworks.com,2005:Question/3376852017-04-27T17:33:05Z2017-04-27T18:20:06Zhow to group data points in matrix<p>Matrix A as follows:</p><pre class="language-matlab">A = [
10
20
5
15
35
40
25
30
5
10
];
</pre><p>Based on the following criteria, I want to give code to every array (X) in matrix A:</p><pre class="language-matlab">if 0 < X <= 5 then code = 1
if 5 < X <= 10 then code = 2
if 10 < X <= 15 then code = 3
if 15 < X <= 20 then code = 4
if 20 < X <= 25 then code = 5
if 25 < X <= 30 then code = 6
if 30 < X <= 35 then code = 7
if 30 < X <= 40 then code = 8
</pre><p>results something like:</p><pre class="language-matlab">out = [
10 2
20 4
5 1
15 3
35 7
40 8
25 5
30 6
5 1
10 2
];
</pre>Amy Xuhttps://fr.mathworks.com/matlabcentral/profile/authors/10119968-amy-xutag:fr.mathworks.com,2005:Question/3376682017-04-27T16:04:25Z2017-04-27T18:19:42Zwhat is the correct formula of (sum of ...from...to...) in matlab<pre> snrin=(-5:5:55); %initial snr
N=length(ecg); % length of ecg signal
n=(0:N-1);
e=sum (ecg^2) from 0 to N-1; **% I want to write this formula correctly**
f=sum (W^2) from 0 to N-1; *% also this*
A=sqrt(e/(10^(snrin/10))*f); *% also this one*</pre>khiter hindhttps://fr.mathworks.com/matlabcentral/profile/authors/9404109-khiter-hindtag:fr.mathworks.com,2005:Question/3376662017-04-27T15:59:39Z2017-04-27T18:16:40ZHow to merge matrices generated from a for loop into one matrix. <pre class="language-matlab">k = 4:.05:6.90
ElementNum = numel(k)
results = zeros(3,numel(k))
for w = 1:numel(k)
A(1,1) = k(w)
solution = rref(A)
solutionV = solution(:,4)
end
</pre><p>The above code is what I have written. I am trying to merge all the solutionV matrices into one matrix. How do I do this?</p>patrick brannanhttps://fr.mathworks.com/matlabcentral/profile/authors/6984675-patrick-brannantag:fr.mathworks.com,2005:Question/3376862017-04-27T17:35:17Z2017-04-27T18:16:20ZHow to create an image from .txt containing coordinates ?<p>I have some .txt files containing 3 columns of number (x,y,z). I should find a way to produce an image file (the format is not important, it may be a .jpg for examples). How can I do that? What are the command rows for that?
Thanks!</p>Lambertohttps://fr.mathworks.com/matlabcentral/profile/authors/5761134-lambertotag:fr.mathworks.com,2005:Question/3376892017-04-27T18:10:06Z2017-04-27T18:15:52Zhow to plot Zakharov function? Can anyone help me pls<p>I want to plot a 2D surface plot of zakharov test function</p>humahttps://fr.mathworks.com/matlabcentral/profile/authors/9568107-humatag:fr.mathworks.com,2005:Question/1310742014-05-25T15:59:09Z2017-04-27T18:12:17ZWhy is the c/c++ code generated by MATLAB Coder not standalone, that is, depends on other library?<p>I write a MATLAB function using some functions from Image Processing Toolbox as follow</p><pre> function Y = TestImageAffine(X, T) %#codegen
H = fspecial('gaussian', 7, 0.5);
X = imfilter(X, H, 'cir', 'same', 'conv');
tform = affine2d(T);
outputView = imref2d(size(X));
Y = imwarp(X, tform, 'OutputView', outputView);</pre><p>The 4 c/c++ code files are gernerated successfully by MATLAB Coder as following</p><pre> TestImageAffine.h
TestImageAffine.c
TestImageAffine_types.h
rtwtypes.h</pre><p>In the c/c++ source file "TestImageAffine.c", 4 header files are included as follow</p><pre> #include "libmwimfilter.h"
#include "libmwippfilter.h"
#include "libmwippgeotrans.h"
#include "tmwtypes.h"</pre><p>For the MATLAB function "Y = TestImageAffine(X, T)" above, MATLAB Coder does NOT gernerate the 4 header files above.</p><p>So My question is that why does MATLAB Coder not gernerate the 4 header files above.</p><p>It is well-known that MATLAB Coder can gernerate "STANDALONE" c/c++ code. Why does the C source file above depend on the other header files?</p><p>Afterwards, I find that the 4 head files exist in the installation path "extern" of MATLAB, and the-same-name files are found as following</p><pre class="language-matlab">libmwimfilter.lib
libmwimfilter.dll
libmwippfilter.lib
libmwippfilter.dll
libmwippgeotrans.lib
libmwippgeotrans.dll
</pre><p>So I think that the generated c/c++ code depends on additional library.</p><p>Finally, I add all the header files, library files and dll files into a Microsoft Visual c++ 2010 project, but the build process fails as follow</p><pre class="language-matlab">" unresolved external symbol _ippgeotransCaller referenced in function _ippgeotrans"
</pre><p>I find out the function "ippgeotransCaller" which is declared in the header file "libmwippgeotrans.h", but I do not know the relationship between ippgeotransCaller and _ippgeotransCaller which appears above</p><p>I do not know what's wrong with my work?</p>chen xbhttps://fr.mathworks.com/matlabcentral/profile/authors/4603690-chen-xbtag:fr.mathworks.com,2005:Question/3376882017-04-27T17:56:57Z2017-04-27T18:08:57ZMATLAB R2017a + Arduino + macOS Sierra<p>I launch a sketch in Arduino that setup connection in this way:</p><pre class="language-matlab">void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("Hello!!");....}
</pre><p>Now I want to run a matlab file.m like this:</p><pre class="language-matlab">port='/dev/cu.usbserial-AI02PH8A'; %the same port seen in Arduino environment
packetSize=24;
Arduino = serial(port,'BaudRate',115200,'InputBufferSize',packetSize);
fopen(Arduino);
fwrite(Arduino,'r');%in the Arduino sketch the command 'r' starts some operations
lastData = fread(Arduino,24);
</pre><p>The problem is that everytime I run the Matlab file it stops giving me the error that the port I choice (the same seen on Arduino environment) doesn't exist.</p><p>If I type <i>instrfind</i> in the command window there are 2 open ports: the one I choose and another named '/dev/tty.usbserial-AI02PH8A'.
Trying to substitute my port with the other one, I receive the same error back.</p><p>I guess it's a problem dealing with macOS Sierra.</p><p>Anyone can provide me a solution different from to remove the cable before running the Matlab file?</p>tempsterhttps://fr.mathworks.com/matlabcentral/profile/authors/9602575-tempstertag:fr.mathworks.com,2005:Question/3376762017-04-27T16:46:23Z2017-04-27T18:31:48ZDifferential Equation Parameter Optimization with Free Time Parameter<p>I am trying to optimize 3 parameters in a system of differential equations using fminunc. The three parameters are theta0, thetaf and tcutoff, which model the initial thrust angle, final thrust angle and engine cut-off time respectively, of a rocket that is launched from the Moon's surface and ends up in a circular 100km orbit around the Moon when its engine is turned off. Below are the functions and main file that perform the optimization and running of the simulation output:</p><p>The first file is main.m, which performs the parameter optimization and runs the simulation once the parameters have been found by fminunc:</p><pre class="language-matlab">clear
clc
close all
format long g
</pre><pre class="language-matlab">%Near optimal solution parameters found using Mathematica's FindRoot function
theta0 = 1.15055; %Initial thrust angle (radians)
thetaf = -0.867385; %Final thrust angle (radians)
tcutoff = 430.086; %Engine cutoff time (s)
</pre><pre class="language-matlab">%Parameter optimization
parameters_init = [0, 0, 450] %Initial parameter guess values
parameters = fminunc(@cost_function, parameters_init)
</pre><pre class="language-matlab">%% Running simulation with parameter outputs
G = 6.672e-11; %Gravitational constant
M = 7.3476e22; %Mass of Moon (kg)
R = 1.737e6; %Radius of Moon (m)
g = 9.81; %Gravitational acceleration on Earth (m/s^2);
mprop = 2353; %Propellant mass (kg)
mstruct = 2150; %Structural mass (kg)
T = 16000; %Total engine thrust (N)
Isp = 311; %Engine specific impulse (s)
mdot = T/(g*Isp); %Engine mass flow rate (kg/s)
tburn = mprop/mdot; %Engine burn time (s)
m0 = mprop + mstruct; %Initial launcher mass (kg)
</pre><pre class="language-matlab">x0 = 0; %Initial x-position (m)
y0 = R; %Initial y-position (m)
vx0 = 0; %Initial x-velocity (m/s)
vy0 = 0; %Initial y-velocity (m/s)
</pre><pre class="language-matlab">rorbit = R+100000; %Desired orbital altitude above Moon's surface (m)
vorbit = sqrt((G*M)/rorbit); %Orbital velocity required to maintain circular orbit at altitude r = rorbit
</pre><pre class="language-matlab">tmax = tburn%tcutoff; %Simulation running time (s)
tspan = [0:tmax]; %Use : notation to produce finer integration steps
xinit = [x0; y0; vx0; vy0; m0]; %Initial conditions
</pre><pre class="language-matlab">[t,x] = ode23t(@(t,x) equations_of_motion(t, x, G, g, M, Isp, T, tburn, parameters), tspan, xinit);
vtotal = sqrt(x(:,3).^2 + x(:,4).^2); %Orbital velocity
vradial = (x(:,1).*x(:,3) + x(:,2).*x(:,4))./sqrt(x(:,1).^2 + x(:,2).^2); %Radial velocity
</pre><pre class="language-matlab">%Plotting
plot(x(:,1), x(:,2))
xlabel('x-position');
ylabel('y-position');
pbaspect([1 1 1])
grid on
figure
plot(t, vtotal)
xlabel('time (s)');
ylabel('Orbital velocity (m/s)');
grid on
figure
plot(1:length(t),vradial)
xlabel('time (s)');
ylabel('Radial velocity (m/s)');
grid on
</pre><p>The second file is cost_function.m, which contains the call to ode45 and calculates the objective function to be minimized by fminunc:</p><pre class="language-matlab">function J = cost_function(parameters)
%function [outputs] = function(inputs)
</pre><pre class="language-matlab">%x = [x1, x2, x3, x4, x5] = state vector = output from ODE solver
%x1 = x-position
%x2 = y-position
%x3 = x-velocity
%x4 = y-velocity
%x5 = mass flow rate
</pre><pre class="language-matlab">%x(end, 1) = x-position at t = tfinal
%x(end, 2) = y-position at t = tfinal
%x(end, 3) = x-velocity at t = tfinal
%x(end, 4) = y-velocity at t = tfinal
</pre><pre class="language-matlab">G = 6.672e-11; %Gravitational constant
M = 7.3476e22; %Mass of Moon (kg)
R = 1.737e6; %Radius of Moon (m)
g = 9.81; %Gravitational acceleration on Earth (m/s^2);
mprop = 2353; %Propellant mass (kg)
mstruct = 2150; %Structural mass (kg)
T = 16000; %Total engine thrust (N)
Isp = 311; %Engine specific impulse (s)
mdot = T/(g*Isp); %Engine mass flow rate (kg/s)
tburn = mprop/mdot; %Engine burn time (s)
m0 = mprop + mstruct; %Initial launcher mass (kg)
</pre><pre class="language-matlab">x0 = 0; %Initial x-position (m)
y0 = R; %Initial y-position (m)
vx0 = 0; %Initial x-velocity (m/s)
vy0 = 0; %Initial y-velocity (m/s)
</pre><pre class="language-matlab">rorbit = R+100000; %Desired orbital altitude above Moon's surface (m)
vorbit = sqrt((G*M)/rorbit); %Orbital velocity required to maintain circular orbit at altitude r = rorbit
</pre><pre class="language-matlab">tmax = tburn;%tcutoff; %Simulation running time (s)
tspan = [0:tmax]; %Use : notation to produce finer integration steps
xinit = [x0; y0; vx0; vy0; m0]; %Initial conditions
</pre><pre class="language-matlab">[t,x] = ode45(@(t,x) equations_of_motion(t, x, G, g, M, Isp, T, tburn, parameters), tspan, xinit);
vtotal = sqrt(x(:,3).^2 + x(:,4).^2); %Orbital velocity
vradial = (x(:,1).*x(:,3) + x(:,2).*x(:,4))./sqrt(x(:,1).^2 + x(:,2).^2); %Radial velocity
</pre><pre class="language-matlab">%Objective/cost function to minimize
%1) Spacecraft must be at r = rorbit when t = tcutoff
%2) Spacecraft must be at v = vorbit when t = tcutoff
%3) Spacecraft must have vradial = 0 when t = tcutoff
J = (rorbit - sqrt(x(end,1).^2+x(end,2).^2)).^2 + (vorbit - sqrt(x(end,3).^2+x(end,4).^2)).^2 + (0 - vradial(end)).^2
end
</pre><p>And the third file, equations_of_motion.m, contains the system of ODEs and the parameter values (theta0, thetaf, tcutoff) to be optimized:</p><pre class="language-matlab">function xdot = equations_of_motion(t, x, G, g, M, Isp, T, tburn, parameters)
%function [ output_args ] = f( input_args )
%t = current time
%x = current state vector (x1, x2, x3, x4, x5)
%g = gravitational acceleration
</pre><pre> %System of equations
%x1 = x-position, x'(t) = vx(t) = x3
%x2 = y-position, y'(t) = vy(t) = x4
%x3 = x-velocity, vx'(t) = ax(t)
%x4 = y-velocity, vy'(t) = ay(t)
%x5 = launcher mass = m(t)
%Note that variable mass x(5)(t) is used as an acceleration term in
%xdot(3)(t) and xdot(4)(t)</pre><pre> theta0 = parameters(1);
thetaf = parameters(2);
tcutoff = parameters(3);</pre><pre> %Linear-tangent steering law
LTS = atan(tan(theta0) - (tan(theta0) - tan(thetaf)).*(t./tburn));</pre><pre> if t <= tcutoff
xdot = [
x(3); %xdot1: x-velocity
x(4); %xdot2: y-velocity
-(G*M*x(1))/((x(1)^2+x(2)^2)^(3/2))+(T/x(5))*cos(LTS); %xdot3: x-acceleration
-(G*M*x(2))/((x(1)^2+x(2)^2)^(3/2))+(T/x(5))*sin(LTS); %xdot4: y-acceleration
-T/(g*Isp) %xdot5: engine mass flow rate
];
else
xdot = [
x(3); %xdot1: x-velocity
x(4); %xdot2: y-velocity
-(G*M*x(1))/((x(1)^2+x(2)^2)^(3/2)); %xdot3: x-acceleration
-(G*M*x(2))/((x(1)^2+x(2)^2)^(3/2)); %xdot4: y-acceleration
0 %xdot5: engine mass flow rate
];
end
end </pre><p>I had previously written the simulation in Mathematica, where the optimal parameter values were theta0 = 1.15055 radians, thetaf = -0.867385 radians and tcutoff = 430.086 seconds, which I've added to the top of the main.m file for reference. It seems that fminunc works beautifully at finding the correct values for theta0 and thetaf. However, the value for tcutoff does not change from the initial guess value that I give using parameters_init in main.m, and I'm sure this is due to me incorrectly implementing the tcutoff parameter using an if statement in the equations_of_motion.m file. As such, I was wondering how I could better implement the third parameter, tcutoff, so that it is able to be optimized to the expected optimal value of tcutoff = 430.086 seconds, instead of not being changed at all. Any help would be much appreciated! Below are the comparison graphs from Mathematica's output, and the current output from MATLAB:</p><p>Mathematica:</p><p>Cartesian xy position when engine turns off:</p><img src = "/matlabcentral/answers/uploaded_files/76342/xy_pos.jpg"><p>Orbital velocity when engine turns off:</p><img src = "/matlabcentral/answers/uploaded_files/76343/orbital_vel.jpg"><p>Radial velocity when engine turns off:</p><img src = "/matlabcentral/answers/uploaded_files/76344/radial_vel.jpg"><p>MATLAB:</p><p>Cartesian xy position when engine turns off:</p><img src = "/matlabcentral/answers/uploaded_files/76345/xy_position.jpg"><p>Orbital velocity when engine turns off:</p><img src = "/matlabcentral/answers/uploaded_files/76346/orbital_velocity.jpg"><p>Radial velocity when engine turns off:</p><img src = "/matlabcentral/answers/uploaded_files/76347/radial_velocity.jpg">JeffR1992https://fr.mathworks.com/matlabcentral/profile/authors/7753323-jeffr1992tag:fr.mathworks.com,2005:Question/3376652017-04-27T15:58:12Z2017-04-27T18:05:46ZReference to non-existent field 'BoundingBox'. Error in findVehicle (line 10) bboxes = regions.BoundingBox; can anyone explain?<pre class="language-matlab">function [bboxes,flow]= findVehicle(frameGray, opticFlow)
</pre><pre class="language-matlab">% Calculate optical flow
</pre><pre class="language-matlab">flow = estimateFlow(opticFlow,frameGray);
</pre><pre class="language-matlab">% Threshold Image
</pre><pre class="language-matlab">threshImage = ( flow.Magnitude > 4);
</pre><pre class="language-matlab">%Find Connected components and filter regions
</pre><pre class="language-matlab">[BW_out,regions] = filterRegions(threshImage);
</pre><pre class="language-matlab">if(size(regions) > 0)
</pre><pre class="language-matlab">bboxes = regions.BoundingBox;
</pre><pre class="language-matlab">else
</pre><pre class="language-matlab">bboxes = [];
</pre><pre class="language-matlab">end
</pre><pre class="language-matlab">end
</pre>Abdullah Lafirhttps://fr.mathworks.com/matlabcentral/profile/authors/9800279-abdullah-lafirtag:fr.mathworks.com,2005:Question/3376672017-04-27T16:00:43Z2017-04-27T18:02:45ZPreviously accessible file is now inaccessible<p>Hi,</p><p>I'm trying to run my code, but I'm getting this error:</p><p>Error using connector.internal.autostart.run
Previously accessible file "D:\Program Files\MATLAB\toolbox\matlab\strfun\num2str.p" is now inaccessible.</p><p>For some reason it is being impossible to convert number to strings. I already try to seth a path to this directory, but nothing has worked yet.</p>Eduardo De Lima Mendeshttps://fr.mathworks.com/matlabcentral/profile/authors/7959541-eduardo-de-lima-mendestag:fr.mathworks.com,2005:Question/3376772017-04-27T16:50:03Z2017-04-27T17:58:33ZTable versus Cell Array to append a disp function that logs steps in a script file<p>Hello, I am new to Matlab and was hoping to get some opinions on the best approach of creating a log file that will ultimately be inserted into SQL at the very end. Throughout the script file I have been writing disp which is great when you use the matlab compiler as it adds it to a log file. But you can't append to it and you can probably use fprintf to append. But, I decided to store in SQL instead. So the question. I would ideally like to create a table in Matlab with Columns defined and append values (will no longer use disp) to that table as the script is run. At the end of the script I will use runstoredprocedure to insert the values from the Matlab table into SQL table. Any ideas? Table or cell array?</p>Mark Mcgrathhttps://fr.mathworks.com/matlabcentral/profile/authors/9869450-mark-mcgrathtag:fr.mathworks.com,2005:Question/3364232017-04-21T02:11:44Z2017-04-27T17:56:41ZHow to reference C code drivers in Simulink Project<p>I am trying to compile code for the TI C2000 TMS320F28377S Processor. When everything is Simulink code, everything I've got compiles fine.</p><p>However, I want to use the Sigma Delta Filter Module which there is no mathworks support for, so I am trying to reference the Control Suite Drivers for this peripheral. The question is, how do I do this and get things to link properly.</p><p>First I added the location of the driver files to my paths in the matlab workspace.</p><p>Second, I set up the Custom Code options as follows in the Model Configuration Parameters as shown below</p><img src = "/matlabcentral/answers/uploaded_files/75707/MATLAB_config_param.JPG"><p>When I compile this, I see the following output in the MATLAB console. The Report Generator gives perfect output, but when it goes to be compiled by Code Composer Studio there is a linker error.</p><pre class="language-matlab"><Linking>
</pre><pre> undefined first referenced
symbol in file
--------- ----------------
_SDFM F2837xS_sdfm_drivers.obj </pre><pre class="language-matlab">error: unresolved symbols remain
error: errors encountered during linking;
</pre><p>It appears that I am not linking the C files correctly. I am just trying to reference the "F2837xS_sdfm_drivers.h" and "F2837xS_sdfm_drivers.c" files from control suite into my simulink project. I then want to call the "Sdfm_configureData_filter" from the C files.</p><p>Any ideas on where I need to put these files for them to be referenced correctly or how I need to reference them in the custom code window?</p>DKalalehttps://fr.mathworks.com/matlabcentral/profile/authors/4330645-dkalaletag:fr.mathworks.com,2005:Question/3376872017-04-27T17:53:36Z2017-04-27T17:55:12ZHow to find area of non overlap region along minor and major axis?<p>Hello,I want to find area of non overlap region along minor and major axis of the skin lesion.I have already get the minor axis and major axis but i dont know how to get the value of area non overlap along major axis and minor axis.
Here are the codes that I have done.</p>wafflehttps://fr.mathworks.com/matlabcentral/profile/authors/9170912-waffletag:fr.mathworks.com,2005:Question/3361782017-04-19T20:14:32Z2017-04-27T17:54:28ZHow to use Bayesian Optimization?<p>I'm trying to run the following Mathworks example with my own X and Y:</p><p>"Tune Random Forest Using Quantile Error and Bayesian Optimization"</p><p><a href = "https://jp.mathworks.com/help/stats/tune-random-forest-using-quantile-error-and-bayesian-optimization.html">https://jp.mathworks.com/help/stats/tune-random-forest-using-quantile-error-and-bayesian-optimization.html</a></p><p>But, I'm getting the following error:</p><pre class="language-matlab">Undefined function or variable 'Y'.
</pre><p>I have attached the modified code (place both files in one folder on your PC drive). Can anyone help?</p>Amy Xuhttps://fr.mathworks.com/matlabcentral/profile/authors/10119968-amy-xutag:fr.mathworks.com,2005:Question/3367092017-04-22T18:40:09Z2017-04-27T17:54:21ZCreate design matrix for ANOVA<p>How can I create a design matrix for ANOVA test manually without writing 0's and 1's (too tedious!!) ?
Such as
[1 1 0 0;
1 1 0 0;
1 0 1 0;
1 0 1 0;
1 0 0 1;
1 0 0 1]</p><p>Thanks in advance!</p>Jihyeon Kimhttps://fr.mathworks.com/matlabcentral/profile/authors/7073524-jihyeon-kimtag:fr.mathworks.com,2005:Question/3375322017-04-27T01:54:36Z2017-04-27T17:53:51ZCurve (Line) Fitting in 3D<p>Hi, I've noticed John D'Errico answering a few of these questions but the polyfitn doesn't seem at first trial to do what I want. But I have some data in x,y,z coordinates. See attached for coordinates. I have manually selected x,y from images based on z = [0:2:100]. However I'm not sure how to fit a curve to this in 3D in order to remove error due to manual selection.</p>Alec Dayhttps://fr.mathworks.com/matlabcentral/profile/authors/6772997-alec-daytag:fr.mathworks.com,2005:Question/3374532017-04-26T16:07:59Z2017-04-27T17:51:07ZHow can I use the value of a variable stored in a cell as a string without using the eval function?<p>Hey folks, I am currently working on a project and I need your help !
Here is what I wanna do :
I’m trying to implement an optimisation process. The names of the variables are saved in a cell containing strings.</p><p>For example :
test={‘a’,’b’,’c’} with a, b and c the names of the variables</p><p>The value of these variables changes at each iteration.</p><p>For one iteration for example :
Variable(1)=10 Variable(2)=20 Variable(3)=30</p><p>I want to assign these values to the corresponding variable in order to run the calculation with the new values of the variables contained in test so I’m doing :</p><p>Assignin(‘base’,test{1},variable(1))</p><p>Hence a=10
Everything is working perfectly so far. The calculation runs and works but at a certain point, I need to know the value of the variable.</p><p>If I execute test{1}, I get ‘a’.</p><p>The only way I find to get the value of a is to use the function eval
Eval(test{1})=10.</p><p>It worked so far but in a few days, I’ll need to compile my Matlab script and I’ve seen that it doesn’t work with eval functions. I would like to find an alternative but I can’t find any.. if some of you have any idea I would be really grateful.</p><p>Cheers !</p>Simon Bhttps://fr.mathworks.com/matlabcentral/profile/authors/9434764-simon-btag:fr.mathworks.com,2005:Question/3345622017-04-10T07:28:40Z2017-04-27T17:51:02ZDetecting faces in video file. Error in using data type<p>I have the following question. I'm working with matlab 2016. I want to detect faces in a video file, using the Viola-Jones algorithm. When I try to enter a video file in & lt;step> the statement, I get the following error:</p><pre class="language-matlab">Error using
vision.CascadeObjectDetector/validateInputsImpl
(line 330)
Expected input number 2 to be
one of these types:
</pre><pre> uint8, uint16, double, single,int16</pre><pre> Instead its type was
vision.VideoFileReader.</pre><pre> Error in VJ1_video (line 12)
bboxes = step(faceDetector, videoFReader);</pre><p>I understand that somehow the type of VideoFileReader should be converted to one of the types: uint8, uint16, double, single, int16. But I do not understand how this can be done. Tell me please. Here is my program code:</p><pre class="language-matlab">clear all;
%Load the video using a video reader object
videoFReader = vision.VideoFileReader('D:\465.avi');
%Create a detector object.
faceDetector = vision.CascadeObjectDetector;
%Detect faces.
bboxes = step(faceDetector, videoFReader);
%Annotate detected faces
IFaces = insertObjectAnnotation(videoFReader, 'rectangle', bboxes, 'Лицо');
%Create a video player object to play the video file.
videoPlayer = vision.VideoPlayer;
</pre><pre class="language-matlab">%Use a while loop to read and play the video frames.
while ~isDone(videoFReader)
videoFrame = videoFReader();
videoPlayer(videoFrame);
end
%Release the objects.
release(videoPlayer);
release(videoFReader);
</pre>Peter Saytsevhttps://fr.mathworks.com/matlabcentral/profile/authors/6682828-peter-saytsevtag:fr.mathworks.com,2005:Question/3376732017-04-27T16:32:50Z2017-04-27T17:47:11ZHow to save normalized data set in file for using it again?<p>I have dataset in csv file. I have normalized it using</p><pre class="language-matlab">Data = rand(10, 20); % Test data, use your data instead
minData = min(Data(:));
maxData = max(Data(:));
scaled = (Data - minData) / (maxData - minData); % Scaled to [0, 1]
scaled = scaled * 2 - 1; % Scaled to [-1, 1]
</pre><p>now the data is normalized, i want to save the normalized data in file again like csv, txt etc.</p>tejasveehttps://fr.mathworks.com/matlabcentral/profile/authors/5271110-tejasveetag:fr.mathworks.com,2005:Question/3375402017-04-27T02:53:01Z2017-04-27T17:46:41ZThermal anaysis Using PDE Toolbox<p>Currently I am conducting thermal analysis using the thermal model in PDE toolbox. I want to study the temperature variation with time of a mechanical assembly which consists of different parts. I exported the assembly from the CAD software as STL file and I read it from MATLAB as follows thermalmodel.Geometry = importGeometry(thermalmaodel,'thermalmodel.stl'). I specified the boundary condition at faces and the initial condition as specified in the documentation. but When I solved I obtained solutions for specific parts which include the boundary condition and other parts haven't should any temperature variation. It seems that the interact between parts need to be specified as boundary condition. I would do appreciate if you let me know how to specify the boundary conditions among parts in multi-part assembly. Thank you in advance for your kind reply.</p>Mohammed Ibrahimhttps://fr.mathworks.com/matlabcentral/profile/authors/5581036-mohammed-ibrahimtag:fr.mathworks.com,2005:Question/3367272017-04-22T21:50:40Z2017-04-27T17:41:41ZHelp with reading/writing an Android to Matlab G-Force program (Android Sensors)<p>Hello, I am currently working on a uni project but I am having a bit of a problem.
I am looking for just a x co-ordinate rotational acceleration vs time and angular velocity (on the x axis, not yaw) program. I have created a drone that rotates and I want to receive the data back to matlab.
Here's what I have so far. Any tips are great.
For some reason the time frames that appear on the graph go to 200 (s) when I pause for 15 s.</p><p>connector on yourpassword;</p><p>m = mobiledev;</p><p>m.AccelerationSensorEnabled = 1;</p><p>m.AngularVelocitySensorEnabled = 1;</p><p>m.Logging = 1;</p><p>pause (10)</p><p>m.Logging = 0;</p><p>[a, t] = accellog(m);</p><p>x = a(:,1);</p><p>y = a(:,2);</p><p>z = a(:,3);</p><p>%plot(t, av);</p><p>% Calculate and plot magnitude acceleration</p><p>mag = sqrt(sum(x.^2 + y.^2 + z.^2, 2));</p><p>figure</p><p>plot(t, mag);</p><p>xlabel('Time (s)');</p><p>ylabel('Acceleration (m/s^2)');</p><p>disp (mag)</p>Anthony Keanehttps://fr.mathworks.com/matlabcentral/profile/authors/7362654-anthony-keanetag:fr.mathworks.com,2005:Question/3376062017-04-27T10:42:29Z2017-04-27T17:41:06ZCan't set breakpoints on changed m-file<p>I run a numerical simulation called "myfile.m". Then I accidentally changed the code of "myfile.m", by accidentally inserting a character somewhere. The file now has an asterisk "myfile.m*". By itself not a big issue, but now I can't debug anymore :( Setting breakpoints gives a gray bullet instead of a red one. And it says "Save file to synchronize breakpoints". When I press "save", it says "Cannot save myfile.m while it is being debugged. Exit debug mode and save?" .... I am kinda scared to do this, because I remember having pressed this before and the whole simulation stopped, not just the debugging. And I don't know what is meant by "Exit debug". I am not debugging anyway. The simulation has been running for 24 hours, and the last time the red bulletpoints worked it showed some very good intermediate results, so I really don't want to waste them. But it will go on for another 24 hours, and I don't have the time, so I want to save the intermediate results stored in the variables, which I can only access using the breakpoints, right?</p>Marloeyshttps://fr.mathworks.com/matlabcentral/profile/authors/10229203-marloeystag:fr.mathworks.com,2005:Question/3298542017-03-14T18:21:17Z2017-04-27T17:39:19Zhow can I use bagofFeatures to classify images? I am working on emotion detection project. I need to classify images and hence I used bagOfFeatures. I tried the following code and it shows only one imageSet.<p>CODE:</p><p>setDir = fullfile(toolboxdir('vision'),'visiondata','imageSets');</p><p>imds = imageDatastore(setDir,'IncludeSubfolders',true,'LabelSource','foldernames');</p><p>[trainingSet,testSet] = splitEachLabel(imds,0.3,'randomize');</p><p>bag = bagOfFeatures(imageSet(trainingSet.Files));</p><p>The output is</p><p>Creating Bag-Of-Features from 1 image sets.</p><ul><li>Image set 1: .</li></ul><ul><li>Selecting feature point locations using the Grid method.</li><li>Extracting SURF features from the selected feature point locations. The GridStep is [8 8] and the BlockWidth is [32 64 96 128].</li></ul><ul><li>Extracting features from 4 images in image set 1...done. Extracted 76800 features.</li></ul><ul><li>Keeping 80 percent of the strongest features from each image set.</li></ul><ul><li>Using K-Means clustering to create a 500 word visual vocabulary.</li><li>Number of features : 61440</li><li>Number of clusters (K) : 500</li></ul><ul><li>Initializing cluster centers...100.00%.</li><li>Clustering...completed 39/100 iterations (~1.78 seconds/iteration)...converged in 39 iterations.</li></ul><ul><li>Finished creating Bag-Of-Features</li></ul>shoba selvarajhttps://fr.mathworks.com/matlabcentral/profile/authors/9709355-shoba-selvarajtag:fr.mathworks.com,2005:Question/3374682017-04-26T17:52:29Z2017-04-27T17:34:31ZHow to get orthogonal eigenvectors for degenerate normal matrix?<p>I know that Matlab can guarantee the eigenvectors of a real symmetric matrix are orthogonal. In fact, for a general normal matrix which has degenerate eigenvalues, we can always find a set of orthogonal eigenvectors as well. But as I tried, Matlab usually just give me eigenvectors and they are not necessarily orthogonal.
Is there any function that can give orthogonal eigenvectors, or is there some fancy alternative way to do it?
Thanks!</p>Zekun Zhuanghttps://fr.mathworks.com/matlabcentral/profile/authors/5550681-zekun-zhuangtag:fr.mathworks.com,2005:Question/3370822017-04-24T20:47:56Z2017-04-27T17:34:08ZNyquist representation of a complex transfer function matrix<p>Hello, i am trying to get this particular representation of a complex transfer function matrix. The problem is, as i am working with a symbolic varible, i do not how to fit the good input argument into the nyquist() function. Here is my program.</p><pre> for i=1:10
gamma(i)=-real(s(i))/wo(i);
end
for l=1:10
D(l,l)=(wo(l)^2-w^2+2*gamma(l)*wo(l)*w);
end
H=subs(Z*inv(D)*conj(Z)');
w=0:1:12;
nyquist(subs(H(1,1)),w);</pre><p>Where wo and gamma are real numbers and Z is a 10x10 matrix with complex numbers. The transfer function is named by H and the symbolic variable is w and from this point i do not know what else to do to get this representation.</p>Javier Mongehttps://fr.mathworks.com/matlabcentral/profile/authors/9733089-javier-mongetag:fr.mathworks.com,2005:Question/3376842017-04-27T17:29:08Z2017-04-27T17:29:08ZHow to construct image with superpixel array values?<p>I have used SLIC algorithm for 50 superpixels and generated 44 superpixels. Based on superpixels, computed meanintensity,area,centroid etc.It gives an array of 44 values.Each array value represents one superpixel.Now the problem is</p><p>Question:How to form image again with modified superpixel array values?</p><p>Please help me</p><p>Thanks in advance.</p>Adhttps://fr.mathworks.com/matlabcentral/profile/authors/9181750-adtag:fr.mathworks.com,2005:Question/807312013-07-01T05:55:33Z2017-04-27T17:28:16Zwhat is the difference between setting continuous or discrete in Power gui block and setting the solver as continuos or discrete?explain in detail<p>what is the difference between setting continuous or discrete in Power gui block and setting the solver as continuos or discrete? differentiate practically to understand</p>Prabhakaran Rajasekaranhttps://fr.mathworks.com/matlabcentral/profile/authors/3588167-prabhakaran-rajasekarantag:fr.mathworks.com,2005:Question/1749672015-02-03T20:40:49Z2017-04-27T17:33:28ZSelf avoiding random walk<p>I need to program a self avoiding random walk, and find the squared mean distance from start to end. I have made the random walk, but as soon as the walk is to long or is repeated to often, it fails. Matlab kinda freezes. I need the chain to be up to 10.000 steps long and repeated at least 100 times, is i my computer that is the problem or is it something else? and how do i fix it?</p><p>kind regards</p><p>distressed student.</p><pre class="language-matlab">function R=saw(N)
d=zeros(1,N);
n=2;
x=zeros(1,N);
y=zeros(1,N);
</pre><pre class="language-matlab">while n<=N
</pre><pre> d(n)=rand;</pre><pre> if d(n)<0.25
x(n)=x(n-1)-1;
y(n)=y(n-1);
elseif d(n)<0.5
x(n)=x(n-1)+1;
y(n)=y(n-1);
elseif d(n)<0.75
y(n)=y(n-1)+1;
x(n)=x(n-1);
elseif d(n)<1
y(n)=y(n-1)-1;
x(n)=x(n-1);
end</pre><pre> r=[x(1:n);y(1:n)]';
ur=unique(r,'rows');</pre><pre> if size(ur)==size(r)
n=n+1;
end</pre><pre class="language-matlab">end
</pre><pre class="language-matlab">R2=x(end)^2+y(end)^2;
R=sqrt(R2);
</pre>Uffe Larsenhttps://fr.mathworks.com/matlabcentral/profile/authors/6138932-uffe-larsentag:fr.mathworks.com,2005:Question/3375032017-04-26T21:47:55Z2017-04-27T17:24:22ZButtonDownFcn on Axes after imshow<p>My ButtonDownFcn for my axes does not work after I call imshow</p><pre class="language-matlab">ax = axes;
set('ButtonDownFcn', @(h,e) disp('Hello'));
imshow(img, 'Parent', ax);
</pre><p>Of course I've read the myriad other post with the same problem and the solution seems to be something like this:</p><pre class="language-matlab">ax = axes;
set('ButtonDownFcn', @(h,e) disp('Hello'));
hold on
h = imshow(img, 'Parent', ax);
set(h, 'HitTest', 'off');
</pre><p>When I do this, it does indeed turn off the hittest for the image, but unfortunately when I click the image I am hitting the figure, not the axes. This is confirmed by the following:</p><pre class="language-matlab">>> hittest()
</pre><pre class="language-matlab">ans =
</pre><pre class="language-matlab">Figure (1) with properties:
</pre><pre> Number: 1
Name: ''
Color: [0.9400 0.9400 0.9400]
Position: [1232 1208 570 450]
Units: 'pixels'hittest()</pre><p><b>So how do I force my click to hit the axes and not the figure?</b> My only work around is to set the ButtonDownFcn for the image itself, but this is really not desirable because after some user input I need to overlay (with transparency) a new image which then becomes the top image. I could then set an identical ButtonDownFcn on this new image, but I'm hoping for a better solution than this work around.</p>Michael Vaianahttps://fr.mathworks.com/matlabcentral/profile/authors/7297328-michael-vaianatag:fr.mathworks.com,2005:Question/3376832017-04-27T17:19:25Z2017-04-27T17:19:25ZHow to get the mean value of the area around certain coordinates of an image?<p>Hi,
I am writing a code to analize all the frames of a video. I have already split the video on its frames.
To simplify my question lets take a single grey scale image.</p><p>I have an image.
I have a mesh of points (with their coordinates). The mesh is a regular square mesh.
I would like to get the average value in the area around each of these points.
And if it is posible to have these mean values in a matrix.</p><p>How do you recomend me to do it?</p><p>Thank you in advance.</p>ferran parerahttps://fr.mathworks.com/matlabcentral/profile/authors/8301132-ferran-pareratag:fr.mathworks.com,2005:Question/3376822017-04-27T17:17:44Z2017-04-27T17:17:44ZHow to preserve a directory structure when packaging an app <p>I created an app that includes a number of subdirectories. Some of these subdirectories contain shell scripts (no *.m extension) which are being invoked by some of the Matlab source files. However, the app package tool does not pick up the non-Matlab files. How can I force the package tool to include all files in all directories?</p>Marinushttps://fr.mathworks.com/matlabcentral/profile/authors/3678697-marinustag:fr.mathworks.com,2005:Question/2259962015-07-01T05:30:57Z2017-04-27T17:17:27Z How can I tell if the parallel computing toolbox installed?<p>I purchased the Linux home version plus the parallel computing toolbox. Home version installed, how can I tell if the parallel computing toolbox installed?</p>J Wigtonhttps://fr.mathworks.com/matlabcentral/profile/authors/6661511-j-wigtontag:fr.mathworks.com,2005:Question/3370962017-04-24T22:15:02Z2017-04-27T17:16:36ZHow to get the transfer matrices for vector transformation?<p>I want to find a real entry square matrices to transfer one symbolic vector to another symbolic vector which in the form of A*x1=x2, A is a square matrices and x1, x2 are vectors. x1 and x2 are given and A is what I want to find.
For example, x1=[f1;f2] and x2=-[f2;f2], then A=[0 -1;0 -1].
I'm not sure how to code it in MATLAB. Could anyone help me?</p>DmArcherhttps://fr.mathworks.com/matlabcentral/profile/authors/8393199-dmarchertag:fr.mathworks.com,2005:Question/2468922015-10-05T15:33:12Z2017-04-27T17:12:40Zhow can find maximum width of object<p>how can I automatically find the maximum width of this object in a binary image? I've shown the maximum width in red line</p><img src = "/matlabcentral/answers/uploaded_files/37985/12.jpg">Abohttps://fr.mathworks.com/matlabcentral/profile/authors/5840315-abotag:fr.mathworks.com,2005:Question/3371872017-04-25T11:36:04Z2017-04-27T17:10:54ZHow to rotate quiver head in 3d in matlab<p>I'm plotting a velocity profile in 3d:</p><img src = "/matlabcentral/answers/uploaded_files/76117/test1.png"><p>To make the arrows in the velocity profile I use "quiver3", the problem is that I want to rotate the arrowhead to be vertical, and not horizontal like they are now. Is this possible to do?</p><p>I tried a solution from another thread that sugested to use:
g = hgtransform;
quiver(x,y,u,v,'Parent',g)
set(g,'Matrix',makehgtform('zrotate',pi/4))</p><p>But I did not get this to work.</p><p>I used:
p2 = plot3((15*data_VP5_U)+13,y, Z,'b-','LineWidth',1.5)
p3 = plot3(x,(10*data_VP5_V)+20, Z,'k-','LineWidth',1.5)</p><p>to plot the lines, and:</p><p>f1 = quiver3(13,y(1),Z(450), (16*data_VP5_U(450)),0,0,'b-','MaxHeadSize',0.8)</p><p>to plot the quiver.</p>Mathias Singsaas Frøsethhttps://fr.mathworks.com/matlabcentral/profile/authors/7612413-mathias-singsaas-frosethtag:fr.mathworks.com,2005:Question/3376012017-04-27T10:24:53Z2017-04-27T17:10:49Zrgb to gray image indeces matching<p>I have an RGB color image with dimensions: 460x640x3 and a gray image with the same dimensions: 460x640. They are of the same type, that is, uint8. I want to get the intensity information of the gray image using the coordinate values from color image if that coordinate value is not black (intensity value ~= 0). if not the intensity value of gray image should be 0 (black).</p><p>If I loop through each values for example like below:</p><pre class="language-matlab">img_length = 460x640;
for i = 1:img_length
if rgbImage(i) ~= 0;
depthImage(i) = i;
else if rgbImage(i) == 0;
depthImage(i) = 0;
i = i+1;
end;
</pre><p>As for color image how can I use only large dimensions as if it is a gray image?</p>Sokhib Tukhtayevhttps://fr.mathworks.com/matlabcentral/profile/authors/7676774-sokhib-tukhtayevtag:fr.mathworks.com,2005:Question/3376702017-04-27T16:26:30Z2017-04-27T17:06:05Zplease help me to define a variable to store the selected face in the current frame<p>I tried to understand the example: Face Detection and Tracking Using Live Video Acquisition. And faced with the following problem. I was not able to understand which of the variables still keeps the face in the current frame. Would someone like to help with this. I need to Supplement this code by identifying faces. For more details, my task is as follows. The detected face in the current frame, in the future it is necessary to recognize whose face it is. But I accordingly do not understand which variable is stored by the selected face. Here this code:</p><pre> % Create the face detector object.
faceDetector = vision.CascadeObjectDetector();</pre><pre> % Create the point tracker object.
pointTracker = vision.PointTracker('MaxBidirectionalError', 2);</pre><pre> % Create the webcam object.
cam = webcam();</pre><pre> % Capture one frame to get its size.
videoFrame = snapshot(cam);
frameSize = size(videoFrame);</pre><pre> % Create the video player object.
videoPlayer = vision.VideoPlayer('Position', [100 100 [frameSize(2), frameSize(1)]+30]);</pre><pre> %% Detection and Tracking
% Capture and process video frames from the webcam in a loop to detect and
% track a face. The loop will run for 400 frames or until the video player
% window is closed.</pre><pre> runLoop = true;
numPts = 0;
frameCount = 0;</pre><pre> while runLoop && frameCount < 400</pre><pre> % Get the next frame.
videoFrame = snapshot(cam);
videoFrameGray = rgb2gray(videoFrame);
frameCount = frameCount + 1;</pre><pre> if numPts < 10
% Detection mode.
bbox = faceDetector.step(videoFrameGray);</pre><pre> if ~isempty(bbox)
% Find corner points inside the detected region.
points = detectMinEigenFeatures(videoFrameGray, 'ROI', bbox(1, :));</pre><pre> % Re-initialize the point tracker.
xyPoints = points.Location;
numPts = size(xyPoints,1);
release(pointTracker);
initialize(pointTracker, xyPoints, videoFrameGray);</pre><pre> % Save a copy of the points.
oldPoints = xyPoints;</pre><pre> % Convert the rectangle represented as [x, y, w, h] into an
% M-by-2 matrix of [x,y] coordinates of the four corners. This
% is needed to be able to transform the bounding box to display
% the orientation of the face.
bboxPoints = bbox2points(bbox(1, :)); </pre><pre> % Convert the box corners into the [x1 y1 x2 y2 x3 y3 x4 y4]
% format required by insertShape.
bboxPolygon = reshape(bboxPoints', 1, []);</pre><pre> % Display a bounding box around the detected face.
videoFrame = insertShape(videoFrame, 'Polygon', bboxPolygon, 'LineWidth', 3);</pre><pre> % Display detected corners.
videoFrame = insertMarker(videoFrame, xyPoints, '+', 'Color', 'white');
end</pre><pre> else
% Tracking mode.
[xyPoints, isFound] = step(pointTracker, videoFrameGray);
visiblePoints = xyPoints(isFound, :);
oldInliers = oldPoints(isFound, :);</pre><pre> numPts = size(visiblePoints, 1); </pre><pre> if numPts >= 10
% Estimate the geometric transformation between the old points
% and the new points.
[xform, oldInliers, visiblePoints] = estimateGeometricTransform(...
oldInliers, visiblePoints, 'similarity', 'MaxDistance', 4); </pre><pre> % Apply the transformation to the bounding box.
bboxPoints = transformPointsForward(xform, bboxPoints);</pre><pre> % Convert the box corners into the [x1 y1 x2 y2 x3 y3 x4 y4]
% format required by insertShape.
bboxPolygon = reshape(bboxPoints', 1, []); </pre><pre> % Display a bounding box around the face being tracked.
videoFrame = insertShape(videoFrame, 'Polygon', bboxPolygon, 'LineWidth', 3);</pre><pre> % Display tracked points.
videoFrame = insertMarker(videoFrame, visiblePoints, '+', 'Color', 'white');</pre><pre> % Reset the points.
oldPoints = visiblePoints;
setPoints(pointTracker, oldPoints);
end</pre><pre> end</pre><pre> % Display the annotated video frame using the video player object.
step(videoPlayer, videoFrame);</pre><pre> % Check whether the video player window has been closed.
runLoop = isOpen(videoPlayer);
end</pre><pre> % Clean up.
clear cam;
release(videoPlayer);
release(pointTracker);
release(faceDetector);</pre>Peter Saytsevhttps://fr.mathworks.com/matlabcentral/profile/authors/6682828-peter-saytsev