https://uk.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2019-02-18T18:35:05Ztag:uk.mathworks.com,2005:Question/4456372019-02-18T18:14:12Z2019-02-18T18:35:05Zgraph multiple fields in a structI have a struct with multiple fields named data1, data2, data3 etc up to 9 I want to graph the first two colums of each field
I used this
position = variable.data1(:,2);
velocity = variable.data1(:,3);
%then i did
plot(position,velocity)
This worked fine but is there anyway to do this in a loop to make it faster? In the future I may have data up to 100s of different arrays Boris Chanhttps://uk.mathworks.com/matlabcentral/profile/authors/11941888-boris-chantag:uk.mathworks.com,2005:Question/4455312019-02-18T09:08:02Z2019-02-18T18:33:28Zhelp with ode solvers non-linear ode 1st law of thermodynamicsHello all:
I am trying to solve the ODE's:
d2y/dt2=-g+(P-Pa)*Ap
dP/dt=k*P*((1/m) *(dm/dt) - (k/(L+y))*(dy/dt))
dm/dt=(m/V) [q-c*Ao*(Pa/P)^(1/k) * {2*k/(k-1) * P*V/m *(1-(Pa/P)^((k-1)/k))}^0.5
V(y)=Ap*(L+y)
where w,Ao,q,Ap,Pa,k,L,g are all constants. but P(t),m(t), y(t) are functions of t
I wrote the following M-file but it looks like it's not working for the m variable. Is there anyting wrong with code or state space variable?
##############################################
clear;close all
global Pa;global A;global Wp;global q;global Ao,global c;global L;global k;
Pa=101000;
d=.05;
Wp=7;
q=2;
Ao=0.01;
c=.1;
L=0.75;
k=1.4;
Te=300;
A=0.25*pi*d^2;
mass=(Pa*L*A)/(287*Te);
tic
W=200;
tf=10;
Fs = .1; %sampling rate
Ts = 1/Fs; %sampling time interval
tspan =0:Fs:tf; %sampling period
y0=[0,.0,101000,mass];
[t,y]=ode45(@Sample01,tspan,y0,[]);
%y[YfreqDomain_d,frequencyRange_d]=positiveFFT(y(:,1),Fs);
subplot(2,2,1);plot(t,y(:,1),'k');
subplot(2,2,2);plot(t,y(:,2),'k');
subplot(2,2,3);plot(t,y(:,3)/Pa,'k');
subplot(2,2,4);plot(t,y(:,4),'k');
dlmwrite('tssst',[y]);
toc
HERE IS THE FUNCTION OF STATE SPACE
function y_dot=Sample01(t,y)
global Pa;global A;global Wp;global q;global Ao,global c;global L;global k;
y_dot=zeros(4,1);
y_dot(1)=y(2);
y_dot(2)=-Wp*9.81/Wp+(y(3)-Pa)*A/Wp;
y_dot(3)=y(3)*((k/y(4))*y_dot(4)-(k/(L+y(1)))*y(2));
y_dot(4)=y(4)/(L+y(1))*(q-c*Ao*(Pa/y(3))^(1/k)*((2*k/(k-1))*y(3)*(L+y(1))/y(4)*(1-(Pa/y(3))^((k-1)/k)))^0.5);
Ahmed Sowayanhttps://uk.mathworks.com/matlabcentral/profile/authors/8027473-ahmed-sowayantag:uk.mathworks.com,2005:Question/4456342019-02-18T17:56:08Z2019-02-18T18:33:24Zhow to get element from matrixfunction btn_forward_Callback(hObject, eventdata, handles)
% hObject handle to btn_forward (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Th_1 = str2double(get(handles.Theta_1,'string'))*pi/180;
Th_2 = str2double(get(handles.Theta_2,'string'))*pi/180;
Th_3 = str2double(get(handles.Theta_3,'string'))*pi/180;
Th_4 = str2double(get(handles.Theta_4,'string'))*pi/180;
L_1 = 10;
L_2 = 20;
L_3 = 30;
L_4 = 10;
L(1) = Link([0 L_1 0 pi/2]);
L(2) = Link([0 0 L_2 0]);
L(3) = Link([0 0 L_3 0]);
L(4) = Link([0 0 L_4 0]);
Robot = SerialLink(L);
Robot.name = 'anosh';
Robot.plot([Th_1 Th_2 Th_3 Th_4]);
T = Robot.fkine([Th_1 Th_2 Th_3 Th_4]);
handles.Pos_X.string = num2str(floor(T(1,4)));
function Pos_X_Callback(hObject, eventdata, handles)
there is error
Index exceeds matrix dimensions.
Error in ggg>btn_forward_Callback (line 188)
handles.Pos_X.string = num2str(floor(T(1,4)));
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in ggg (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)ggg('btn_forward_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callback.
ans sobhihttps://uk.mathworks.com/matlabcentral/profile/authors/8484055-ans-sobhitag:uk.mathworks.com,2005:Question/4456352019-02-18T18:07:21Z2019-02-18T18:32:19ZI have a large vector, I would like to find a set of data which is a subset of the large vector.Any algorithm I can use to find the set of data?Yun Zhanghttps://uk.mathworks.com/matlabcentral/profile/authors/10731430-yun-zhangtag:uk.mathworks.com,2005:Question/4456392019-02-18T18:29:55Z2019-02-18T18:29:55ZDoes the Neural Network created by the Neural Network Toolbox be used in the Android application made ?Hello, I have used the Neural Network Toolbox to train my system to read certain images and give a certain output. Now I'm planning on making an Android app for the same system and was wanting to know if the saved Neural Network can be used in the android application too?
Also which is the best way to create an app for android using MATLAB code?amogh BHATNAGARhttps://uk.mathworks.com/matlabcentral/profile/authors/8520037-amogh-bhatnagartag:uk.mathworks.com,2005:Question/4456382019-02-18T18:21:42Z2019-02-18T18:29:14Z How can I delete the repeated values and keep just a row of each one? I have this matrix
[3 11 43;
3 17 41;
3 41 17;
3 43 11;
11 3 43;
11 43 3;
17 3 41;
17 41 3;
41 3 17;
41 17 3;
43 3 11;
43 11 3 ]
The result should be something like this [ 3 11 43; 3 17 41 ]
OBS. I tried unique() and it didn't work as I want.DShttps://uk.mathworks.com/matlabcentral/profile/authors/14043820-dstag:uk.mathworks.com,2005:Question/4454352019-02-17T17:30:34Z2019-02-18T18:29:02ZHow can I group column of data with the same time stamp and get the row mean of each group?
from this table to this image where
x = Height
t = time
u = zonal wind
Teddy2018https://uk.mathworks.com/matlabcentral/profile/authors/14804435-teddy2018tag:uk.mathworks.com,2005:Question/4456362019-02-18T18:11:46Z2019-02-18T18:13:00ZHow to peform multiple paired-t testsTo my knowledge
ttest.m
can be used to peform a single parired t test, e.g., ttest(x,y), and the function can also be used for mutiple paired t tests when it is called many times. I wonder if there are some functions for multiple paired ttests, e.g., among x1, x2, x3 and x4, without calling ttest.m many times? Yuzhen Luhttps://uk.mathworks.com/matlabcentral/profile/authors/8338519-yuzhen-lutag:uk.mathworks.com,2005:Question/4451772019-02-15T15:23:45Z2019-02-18T18:12:03ZError writing name_file.m. Access denied.Hi everyone, I have a sudden problem when I try to save or run the file. The error window say "Error writing name_file.m. Access denied". It's really strange because it has always worked well. I tryed to:
Change path location
Open Matlab as administrator
Change Matlab version from 2016 to 2018
Change Matlab file
But i have always the same problem. I can not understand what the problem could be. This is the screenshot:
michele paolettihttps://uk.mathworks.com/matlabcentral/profile/authors/9117418-michele-paolettitag:uk.mathworks.com,2005:Question/4456212019-02-18T17:17:06Z2019-02-18T18:11:05Zsaving the drawn lines into text file to use it to generate a 3D part in solidworkshi every body
I generated an elliptical gear and I am trying to save the coordinates of all the points into text file ( the teeth profile and the root curve seperately) to be able to generate these curves in SOILDWORKS and test the 3D gear.
I am wondering ( since my experience in MATLAB is not that good :( ) what is the fucntion or methodolgy can be used to get this
note:
the blue curve is the root curve and it has been generated by an direct equation
the black curves are the teeth profiles and they have been generated in ( for) loop with same number of the teeth number.
sorry if my question was very simple comparing to your experiences friends.
thanks in advance for every body .
nezir elalihttps://uk.mathworks.com/matlabcentral/profile/authors/14103856-nezir-elalitag:uk.mathworks.com,2005:Question/4456292019-02-18T17:39:54Z2019-02-18T18:10:05ZMatch cell array of strings to table row names I have a table T1 of unique row names and corresponding weights (size is around 7000 rows)
T1:
row name WEIGHT
raining -1.3
house 3.5
happy 5
etc... (7000 rows)
I have a smaller (~100 row) cell array CA1 of strings, some of which appear in T1, some of which don't. Strings can be repeated in CA1.
CA1:
house
my
feet
raining
raining
etc... (100 rows)
I want all the matches between CA1 and T1 and, for these matches, to return a sum of the weights.
In the example above the output would be: 3.5+0+0-1.3-1.3 = 0.9 (since 'my', and 'feet' don't appear in T1 (hence the zeros) but 'house' and 'raining' do - with 'raining' appearing twice)
I can't make CA1 a table, since the row names wouldn't be unique. If a string appears n times in CA1 i want to have that weight added n times to my final sum.
I've checked the documentation, read a number on answers on this forum, but can't find how to do this. Using strcmp would seem to require an ugly and time consuming loop. I would appreciate any help. Thanks
Richard Clarkehttps://uk.mathworks.com/matlabcentral/profile/authors/10012001-richard-clarketag:uk.mathworks.com,2005:Question/85342011-05-31T17:51:38Z2019-02-18T18:10:00ZReplacing elements of an array with a vectorI know that you can select elements out of a matrix that meet a condition and assign a new value, i.e.
a = [1 2 3 4 5 6 7 9];
a(a>4) = 0;
a
1 2 3 4 0 0 0 0 0
but what if you have a multidimensional matrix? I want to do something similar to the following:
a = [1 2 3 4; 0 0 0 0];
a(a(1,:)==1) = [a b];
a
a 2 3 4
b 0 0 0
The situation is that I have a matrix where the first three dimensions are spatial and then there's a fourth that contains information about the spatial element. Right now, I'm using For loops to check every element and assign a vector [a b c d] to the spatial element. I would like to vectorize this and it's frustrating how easy it is to do this with one scalers, but it doesn't work with vectors.Greggoryhttps://uk.mathworks.com/matlabcentral/profile/authors/2867817-greggorytag:uk.mathworks.com,2005:Question/4456322019-02-18T17:44:03Z2019-02-18T18:09:11ZIssue while generating code for Infineon XMC4500 in 2018aI am a beginner in MATLAB Embedded Coder. In Matlab R2018a (with update 6), I want to develop C-code for Infineon XMC 4500 target for academic puposes. I have installed "Embedded Coder Support Package for ARM Cortex-M processor" and "DSP System Toolbox Support Package for ARM Cortex-M Processors" for the same. I then installed "XMC Library for Embedded Coder" v2.0.
After opening any specific example from the XMC Library, when I select the "Infineon_XMC_Family.tlc" in the STF selection menu in Configuration Parameter of Simulink menu, I see following messages in the matlab editor:
Info: ARM CORTEX-M Support Package not found.
Info: ARM CORTEX-M Support Package not found.
Info: SEGGER J-Link installation not found.
I can see the support packages installed in Add-On Manager.
The "CMSIS Library Path" and "Compiler Path" are empty in the "XMC Target Options" subsection of "Code Generation" in Model Configuration Parameters for Simulink. However, while navigating to MATLAB Help > Embedded Coder > Supported Hardware, I can see ARM Cortex-M Processors.
After I start the build procedure this is the output from diagnostic viewer: (regardless of data in "CMSIS Library Path" and "Compiler Path", generate code only):
Following is the Stack trace, that I took from build_exception.mat from the [project name]_xmc_rtw folder:
The model.rtw is sucessfully created and parsed by tlc. In the model_xmc_rtw folder, I see only one folder named "tlc" and 3 files: buiild_exception.mat, codedescriptor.dmr and the model.rtw file. Inside tlc folder, some code specific tlc files are present.
What I have tried and doesn't works:
Reinstalling "Embedded Coder Support Package for ARM Cortex-M processors", "DSP System Toolbox Support Package for ARM Cortex-M Processors" and "XMC Library for Embedded Coder" ( multiple times )
Reinstalling MATLAB ( same version ).
Added echo, $(info), $(warning) etc. in "Infineon_XMC_Family.tmf" file to see whether gmake is executing the tmf file. No respective message is seen on diagnostic viewer or matlab editor (might be internally supressed). (note SHELL = cmd in tmf file)
Adding/Removing CMSIS path and Compier Path in Configuraiton Parameters/Code Generation. However, entering wrong path format (addition literals in path) gives error in the Diagnostic viewer.
Siddharth Lakherahttps://uk.mathworks.com/matlabcentral/profile/authors/10662835-siddharth-lakheratag:uk.mathworks.com,2005:Question/4452462019-02-16T00:52:49Z2019-02-18T18:04:17ZConditionally Defining a Variable using ODE45How could I take this code I'm using and conditionally define my variable 'p'? For example, I want p=0 everywhere except when 3<t<4, then I want p=1.2. Here is my code:
tspan=[1 7];A0=1;P0=1;g=1;p=0;B=0.15;
[t,x] = ode45(@(t,x) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)], tspan, [A0 P0]);Thomas Veithhttps://uk.mathworks.com/matlabcentral/profile/authors/13550529-thomas-veithtag:uk.mathworks.com,2005:Question/2328382015-08-07T21:01:34Z2019-02-18T17:59:13Zlsqcurvefit : undefined values at initial pointa.mat contains the output of a ccd camera.
y = transpose(mean(a));
x = transpose(1:1280);
x0 = [600 1e4 .01];
parfit = lsqcurvefit(@fraunhof,x0,x,y)
function F = fraunhof(x,xdata)
beta = x(3).*(xdata-x(1));
sinbeta = sin(beta);
F = x(2).*sinbeta.^2./beta.^2;
Running this code returns the following error:
Error using snls (line 47)
Objective function is returning undefined values at initial point. lsqcurvefit cannot continue.
Error in lsqncommon (line 150)
[xC,FVAL,LAMBDA,JACOB,EXITFLAG,OUTPUT,msgData]=...
Error in lsqcurvefit (line 253)
[xCurrent,Resnorm,FVAL,EXITFLAG,OUTPUT,LAMBDA,JACOB] = ...
G Guerrerhttps://uk.mathworks.com/matlabcentral/profile/authors/6721051-g-guerrertag:uk.mathworks.com,2005:Question/4455842019-02-18T14:23:14Z2019-02-18T17:57:04ZWhat is the solution for below code? It shows error t=0:0.001:2; %sec @ 1 khz sample rate
x=chirp(t,0,1,150); %start @ DC ,cross 150 HZ at t=1 sec
F=0:.1:100;
[y,f,t,p] = spectrogram (x,256,250,F,1E3,'yaxis');
% this is the same as calling spectrogram with no outputs
surf(t,f,10*log10(abs(p)),'edgeColor','none');
axis xy; axis tight; colormap(jet);view(0,90);
xlabel ('time');
ylabel('Frequench (HZ)');
[y,fs] =audioread('filename.wav');
NW=round(fs*0.025);
[,F,T,P]= spectrogram(y,NW,[],[],fs);
Error using Spectrogram>chkinput (
line252)
Xmust be a vector(either row or column)
Error in spectrogram (line166) chkinput (x);
Yasir Alihttps://uk.mathworks.com/matlabcentral/profile/authors/14557848-yasir-alitag:uk.mathworks.com,2005:Question/4456332019-02-18T17:49:48Z2019-02-18T17:55:21ZWhy is my CSV reader not working?clc; clear;
% Path to Data Files.
path = "C:/Users/Desktop/File Names";
% Number of F & G.
No_F = 32; No_G = 32;
% Defines the first ten file names by adding the '0' infront of the file number.
for i = 0:9;
fname(i + 1) = strcat("i_0", string(i), ".CSV");
fnamelabel(i + 1) = strcat("i\_0", string(i));
end
% Defines the rest of the file names using the given file number.
for i = 10:No_F-1;
fname(i + 1) = strcat("i_", string(i), ".CSV");
fnamelabel(i + 1) = strcat("i\_", string(i));
end
% Reads the time column from the first measurement.
% time = csvread(strcat(path,fname(1)),1,0,[1,0,10000,0]);
time = csvread('i_00.CSV', 1, 0, [1, 0, 10000, 0]);
for i = 1:No_F;
temp = strcat(path, fname(i));
data(:,:,i) = csvread(temp, 1, 1, [1, 1, 10000, No_F]); %%%% Error using csvread, File not found.
end
The line that doesn't work is:
data(:,:,i) = csvread(temp, 1, 1, [1, 1, 10000, No_F]);
Brandon Hubbardhttps://uk.mathworks.com/matlabcentral/profile/authors/4559862-brandon-hubbardtag:uk.mathworks.com,2005:Question/4456162019-02-18T16:43:57Z2019-02-18T17:51:52Z row wise Inner product of two matrices without using loopI have two matrices A= 40 x 50 and B = 61 x 50. I want to get the row wise dot product for the entire combination of rows of two matrices. Using for loop it is something like this
for i=1:40
for j=1:61
inner_prod(i,j) = dot (A(i,:),B(j,:);
end
end
Is there any way to do this avoiding the for loop and less execution time ?sandeep pandeyhttps://uk.mathworks.com/matlabcentral/profile/authors/7793402-sandeep-pandeytag:uk.mathworks.com,2005:Question/4456122019-02-18T16:26:45Z2019-02-18T17:47:05ZState Space block state vector valueHello,
I am using Simulink built in state spacestate space block. The input to this block is u, and the output is y.
I also need the x value, the state vector. How can I extract this value from the built in state space block.
Raha Hojjatihttps://uk.mathworks.com/matlabcentral/profile/authors/8719422-raha-hojjatitag:uk.mathworks.com,2005:Question/4454962019-02-18T03:53:18Z2019-02-18T17:45:42ZLooking for candlestick, rsi, csv file exampleNormally for python and other languages, if i search such keywords candlestick+rsi+csv, i can find plenty of examples.
Now i'm learning matlab, cannot find proper samples yet, so want to start with dummy questions, pls bear with me.
i got this:
Data = readtable('/home/usr1/matlab/spy.csv')
now i want to draw the candlestick and rsi in the same figure, can someone show me a simple code to get started ?
My question is, i don't know the latest correct ways, some examples are from 2011 and won't compile in the latest matlab version.
Thanks !
Ning Jihttps://uk.mathworks.com/matlabcentral/profile/authors/14560433-ning-jitag:uk.mathworks.com,2005:Question/4456312019-02-18T17:42:41Z2019-02-18T17:42:41ZPulse random generator issueHello,
I'm new in Simulink and i trying to make a pulse random generatorpulse random generator. Pulses have amplitude (1 ) and width (6 nano sec). The signal has to be periodic. how can i do it? I apprecitate any help.
Thanks. ibra01https://uk.mathworks.com/matlabcentral/profile/authors/10084764-ibra01tag:uk.mathworks.com,2005:Question/4456302019-02-18T17:41:32Z2019-02-18T17:42:14ZExtend a vector with different stepsHey,
I've got vector(1x400). I would like to extend it into 1x140000 vector. The source vector comprises 2 values( 0 and 7). Every level comes after other 0 -> 7 -> 0 etc. But every step represents time step and i would like to keep this time step but extend in number of samples. For example: 1st 0 level lasts 3 secs, and 40 samples in source vector. I want to extend(or make at least) vector where 1st 0 level will last 3 secs but it should have 350 samples. Is there any option to do it?Carol Downeyhttps://uk.mathworks.com/matlabcentral/profile/authors/14552272-carol-downeytag:uk.mathworks.com,2005:Question/4456282019-02-18T17:38:48Z2019-02-18T17:38:48ZSpatial smoothing - 2D MUSIC [FMCW MIMO radar processing] Hi everyone,
I'm using a 2D Music algorithm for the estimation of Range-Azimuth info in a ULA FMCW MIMO radar.
The algorithm procedure is pretty simple (see "Belfiori F., Application of 2D MUSIC Algorithm to Range-Azimuth FMCW Radar data" or " Manokhin G., MUSIC-based algorithm for range-azimuth FMCW radar data processing without estimating number of targets"). I have some doubt with regard the application of the 2D FB spatial smoothing in order to decorrelate the covariance matrix of the data; I'm wondering if I do some error in the following code section (in the way I order the x_win_new vector):
x= DataV'; %Data collected by the ULA (31 Spatial samples-31Antennas), 501 time samples
N = size(x,1); % Number of antennas
M = size(x,2); % Number of samples in fast-time dimension
% window dimension for the smoothing dim[m1xm2]
m1 = 25;
m2 = 300;
p1 = N-m1+1; %positions in the spatial dimension
p2 = M-m2+1; %positions in the time dimension
N_submat = p1*p2; %number of all the possible scan
M_tot = m1*m2;
ind_tot=1;
for p1_ind = 1:p1
for p2_ind = 1:p2
x_win_new(:,ind_tot) = reshape (x(p1_ind:m1+(p1_ind-1),p2_ind:m2+(p2_ind-1)),[1,M_tot])';
ind_tot=ind_tot+1;
end
end
X_win_cor = x_win_new*x_win_new';
X_win_cor_conj = conj(X_win_cor);
J= fliplr(eye(M_tot)); %transition matrix
C=(1/2*N_submat)*(X_win_cor + J*X_win_cor_conj*J); %data smoothed covariance matrix (forward+backward)
so in my case I'm scanning the full 2D [NxM] matrix in this way:
x x x . . x x x . . . . . . . .
x x x . . x x x x x x . . x x x
x x x . . x x x x x x . . x x x
. . . . . . . . x x x . . x x x
If I select m1=M and m2=N (so no spatial smoothing, only forward/backward averaging) I get good results as shown in the attached image.
Thanks a lot in advance,
Best regards,
Luca,Luca Romanohttps://uk.mathworks.com/matlabcentral/profile/authors/7358657-luca-romanotag:uk.mathworks.com,2005:Question/4450332019-02-14T19:18:58Z2019-02-18T17:36:59ZSolve nonlinear equation with different parameters Hello,
I would like to solve a (quite complicated) equation that looks like this:
pi/2*C*x + 0.5*(3 - gamma^2 - 2*gamma)*C*V^2 + 2*A*V + 2*x*B^2 - pi/2*F;
where gamma is also a function of x and it's defined as following:
gamma = gamma0*exp(-D*atan((B*x)./(C*Vdc)))*sqrt(1+((B*x)/(C*V)));
So, in the end, it can be considered as one (long) equation.
The unkowns are x and Vdc. I was thinking of defining the value of Vdc as a linsopace vector, for example, and see the value of x for each variation of Vdc (by making a loop). The question is: how can I solve the equation?
Also, would it be possible to solve the same equation by making varying other parameters of it (by making a loop on them)?
Thank you in advance for your help! letoppinahttps://uk.mathworks.com/matlabcentral/profile/authors/8974289-letoppinatag:uk.mathworks.com,2005:Question/4456182019-02-18T17:13:07Z2019-02-18T17:32:58ZDisplaying for loop iterations as a matrix for R=0.6:0.05:0.95;
A=[(1.5*R-1.59), 0.5*R, 0; 0.5, -21.75, 0; 0, 0, 0];
B=[-0.7; -38; 0];
a=Guass(A,B);
Ci= a(2,2)/a(2,4)
Cu= (a(1,4)-a(1,2)*Ci)/a(1,1)
Liver= [R;Ci]
Lung= [R;Cu]
end
So this code will display Ci and Cu as its individual outputs for each iterations, but I want it displayed as a matrix but when I try displaying Liver and Lung it only displays the last iterations. How can I make it display all the iterations?Abigail Osbornehttps://uk.mathworks.com/matlabcentral/profile/authors/9536628-abigail-osbornetag:uk.mathworks.com,2005:Question/4456272019-02-18T17:31:24Z2019-02-18T17:31:24ZHow i can vectorize the above part of my code?i want to ask how i can vectorize the above part of my code
With Great Honours Dimitrios GerontitisDimitrios Gerontitishttps://uk.mathworks.com/matlabcentral/profile/authors/4715161-dimitrios-gerontitistag:uk.mathworks.com,2005:Question/4456132019-02-18T16:27:58Z2019-02-18T17:26:42ZHow to store output of a for loop in a matrix?Hi guys,
I'm having difficulty storing my output values from a loop into a matrix. And whenever I try the solution mentioned in other examples the error preallocate comes up.
My code is below:
P= [10 20 30]
A=1230
B=0.14
Idir=0
for index = 1:3
Idir=(A/(exp(B/sin(P(index)))))
endJamil Dudhwalahttps://uk.mathworks.com/matlabcentral/profile/authors/14547273-jamil-dudhwalatag:uk.mathworks.com,2005:Question/1518432014-08-21T18:31:02Z2019-02-18T17:26:21ZLicense manager Error -114 , Need to fix?Need you help.............After installation of Matlab 2014a.I found an error...Need to fix this error. If the error is due to license ,kindly send me license file if you have. Any effort will be strongly appreciated..Thanks
<</matlabcentral/answers/uploaded_files/17101/Capture.PNG>>azizullah khanhttps://uk.mathworks.com/matlabcentral/profile/authors/3587681-azizullah-khantag:uk.mathworks.com,2005:Question/4456242019-02-18T17:20:58Z2019-02-18T17:26:13ZHow to use a Kalman filter to integrate accelerationHi
I have vertical acceleration over time (of jumps) and I need to perform double integration to obtain the displacment.
It seems that kalman filters are able to take care of noise and the drift usually found in this procedure. However i never used a kalman filter and have no idea of what to do to get the second integral using a kalman filter.
Note: I already have done an algorithm (bellow explained ) to do this but I need to see what procedure can give better results.
Algorithm already made:
1) The acceleration signal was detrend
2) The acceleration was filtered with a low pass filter
3) Using a cumsimps (i.e. cumulative simpson rule) function the velocity was obtained by 1º integration
4) The velocity signal was filtered with a high pass filter
5) Using a cumsimps (i.e. cumulative simpson rule) function the displacement was obtained by 2º integration
Can anyone help me with the kalman filter please to achieve similar results.
Note a txt file is attached with some acceleration data.
Aurelio F.https://uk.mathworks.com/matlabcentral/profile/authors/14814630-aurelio-ftag:uk.mathworks.com,2005:Question/4456262019-02-18T17:24:52Z2019-02-18T17:24:52ZHow to get consistent subplot widths with legend outside?I want to put my legends outside the plot so they never cover any data, but also want the subplots to have the same width since they'll all have the same X data. If the legends have variable width, the auto-positioning makes the sub plots different widths. Is there anyway to get around this?
Nickhttps://uk.mathworks.com/matlabcentral/profile/authors/2914053-nicktag:uk.mathworks.com,2005:Question/4456252019-02-18T17:23:21Z2019-02-18T17:23:21ZWatermark using 2 level dwt,fast hadamard transform and svdhello can u pleasehelp to generate matlab code for image watermarking using 2level dwt ,fast hadamard transform and svd.please its very urgent .help meKaviarasi Ezhumalaihttps://uk.mathworks.com/matlabcentral/profile/authors/14625288-kaviarasi-ezhumalaitag:uk.mathworks.com,2005:Question/4456222019-02-18T17:19:46Z2019-02-18T17:22:52ZMeasure Angular Position with an Incremental Rotary EncoderHi everybody,
I am trying to measure angular position with an incremental rotary encoder with NI DAQ card. I can not reset with Z-axing my encoder. I want to make a limit from 0 to 360 degrees, but I coudnt do it. I want to share my code that I got from mathworks:
https://www.mathworks.com/help/daq/examples/measure-angular-position-with-an-incremental-rotary-encoder.html
But the last part of the code ( Z signal part ) is not working;
here is the code:
s = daq.createSession('ni');
ch1 = addCounterInputChannel(s, 'Dev1', 0, 'Position')
ch1.EncoderType = 'X1';
addAnalogInputChannel(s, 'Dev1', 0, 'Voltage'); // I need to put an analog input to automatically share this system's scan clock.
s.Rate = 10000;
s.DurationInSeconds = 15; // my duration in seconds
ch1.ZResetEnable = true; // I am making enable Z-axing
ch1.ZResetCondition = 'BothLow';
ch1.ZResetValue = 0;
[positionData, timestamps] = startForeground(s);
// making a threshold
counterNBits = 32;
signedThreshold = 2^(counterNBits-1);
signedData = positionData(:,1);
signedData(signedData > signedThreshold) = signedData(signedData > signedThreshold) - 2^counterNBits;
positionDataDeg = signedData * 360/encoderCPR;
figure; plot(timestamps, positionDataDeg);
xlabel('Time (s)');
ylabel('Angular position (deg.)');
I can not reset my Z value and get my degrees from 0 to 360 degrees. Can you please help if you have information about this,
Thanks a lot,
Ceyhun Ibolarhttps://uk.mathworks.com/matlabcentral/profile/authors/14034257-ceyhun-ibolartag:uk.mathworks.com,2005:Question/4454722019-02-17T22:32:27Z2019-02-18T17:21:01ZHow to add markers to a videoHello,
so I'm working on a motion tracking project of sorts and so far i have already achived my initial goal of finding the coordinates of a moving light.
My current problem is that I'm trying to add a path of markers (like the picture below) to the video so it would show the light tracking the path, while i have achived doing this with a static picture i just can't figure the way to do the same with a video
Any help would be appreciated, Thanks in advance
UPDATE: I managed to get the job done by turning the video to a image sequence and then back to a video, still interested in finding a way to add markers to a video without going through all thatsohrab maouhttps://uk.mathworks.com/matlabcentral/profile/authors/12735127-sohrab-maoutag:uk.mathworks.com,2005:Question/4456232019-02-18T17:20:35Z2019-02-18T17:20:35ZExternal trigger to start recording of multiple framesI would like to start recording a certain number of frames after an external trigger has been detected. The following code just records a single frame each time the external trigger is detected. I was expecting 600 frames in this example, because the parameter vid.FramesPerTrigger is set to 600.How can i detect N frames with a certain fps if triggered instead of just one single frame?
"start"
clear all
vid = videoinput('tisimaq_r2013_64', 1, 'Y800 (1280x1024)');
config = triggerinfo(vid);
s = vid.Source;
triggerconfig(vid, 'hardware', 'hardware', 'hardware');
vid.FramesPerTrigger = 600;
vid.TriggerRepeat = 0;
start(vid);
wait(vid, 10);
stop(vid);
[data,d] = getdata(vid, vid.FramesAvailable);
"end"Oliver Köhnhttps://uk.mathworks.com/matlabcentral/profile/authors/10651397-oliver-kohntag:uk.mathworks.com,2005:Question/4456082019-02-18T16:06:26Z2019-02-18T17:19:42ZCan't run an equation in a function that works in a scriptHi,
I've used the following code for an equation in MATLAB and it works perfectly well in a script (cp1 and u1 have already been defined):
syms u4
eqn3 = cp1 == (u1+u4)*(u1.^2-u4.^2)/(2*u1.^3);
U4= double(solve(eqn3,u4));
u4 = real(U4( U4 > 0 ));
However, when I've tried to implement it into a function it doesn't work.
Can anyone help me with this please?Daniel Harperhttps://uk.mathworks.com/matlabcentral/profile/authors/9567165-daniel-harpertag:uk.mathworks.com,2005:Question/4456202019-02-18T17:15:57Z2019-02-18T17:15:57ZRecover a corrupt mat file v7.3, ran out of disk spaceHi,
I have a corrupt v7.3 mat file. I ran out of disk space while writing to it using matfile. It contains data from a 1 week computation, so I'd really like to try to open it.
When I try to call matfile() on it, I get the error: Unable to read MAT-file filename.mat: not a binary MAT-file.
I searched around and found the the splitmat function, which can help sometimes. This didn't work for my file.
Thanks for your kind help,
TRThomas Richnerhttps://uk.mathworks.com/matlabcentral/profile/authors/10931375-thomas-richnertag:uk.mathworks.com,2005:Question/4456172019-02-18T17:12:38Z2019-02-18T17:13:23ZHow to load set of images into workspace for training?I'm working on currency recognition. How can i apply set of images of currency notes into workspace in matlab to use for training? Hiruni Gunawardhanehttps://uk.mathworks.com/matlabcentral/profile/authors/14363488-hiruni-gunawardhanetag:uk.mathworks.com,2005:Question/4456192019-02-18T17:13:16Z2019-02-18T17:13:16ZHow can we translate the fonction 'save' in a way that C++ MATLAB Coder could transform it correctly?Hi,
we are trying to transform a MATLAB function into C++ using the MATLAB Coder. The below script is part of the function and they are causing the problem...
We have
A.
pFile = fopen ("ex122a.dat","w");
Thk122=[thk122(:,1)];
for i=2:141
Thk122=[Thk122; thk122(:,i)];
end
ex122=[Lon Lat Thk122];
ex122a=rot90(fliplr(ex122));
fprintf(pFile,'%10.6e %10.6e %10.6e\n',ex122a);
fclose(pFile);
B.
Thk122=[thk122(:,1)];
for i=2:141
Thk122=[Thk122; thk122(:,i)];
end
ex122=[Lon Lat Thk122];
save ex122.dat ex122 -ascii;
Both generate the proper file in Matlab as ex122a.dat (A) is the same as ex122.dat (B). ex122 is a matrix 10716x3 double and we want the output as a list with 3 columns with 10716 lines. Those two parts A and B work, which we used for translating the function 'save' in a simpler way for coding in C++ as 'save' is not supported by MATLAB Coder. However, if we are using the latter, we get a 'Generation of trial code failed' for A with the the description:
'An argument corresponding to the conversion character 'e' in the 'formatSpec' parameter in not scalar. Array input is not supported to code generation. It must be a fixed scalar'
while for B the 'Function 'save' is not supported for code generation and the coder.extrinsic directive cannot be applied.', which is expected.
After a search on the web, we have found MathWorks Support for our scalar expansion issue but it does not work...
HOW could we transform the function 'save' from MATLAB to C++ by going through MATLAB Coder?F Lapointehttps://uk.mathworks.com/matlabcentral/profile/authors/6927498-f-lapointetag:uk.mathworks.com,2005:Question/4455142019-02-18T06:31:33Z2019-02-18T17:12:23Zhow to change the color of lung portion only from binary image?fatimahttps://uk.mathworks.com/matlabcentral/profile/authors/14809986-fatimatag:uk.mathworks.com,2005:Question/4455922019-02-18T15:17:38Z2019-02-18T17:01:16ZHelp optimizing inefficient code I'm relatively new to matlab, and I have a code for merging two datasets based on a common attribute (in this case names). However, my code is very inefficient, so I'd be grateful for any suggestions to make it more efficient.
The gist of it is this: I have two datasets. They have complementary data, and share certain attributes that I'd like to use to combine them. I'm reading Dataset 1 as a cell array. It contains promoters names (which I'll just call promoters), and a value associated with each.
I've been reading Dataset 2 as a table then turning it into cell array. Each row represents one gene, however each gene can possess no promoters, one promoter, or multiple promoters (which I'll just call 'Names' from now on) from dataset 1. I'd like to find a way to append the value in dataset 1 to it's associated identifier as well as gene in dataset 2. In dataset 2, if a gene has multiple promoters they are originally stored in a single string cell and are separated by: ' // '
Essentially:
Dataset 1 (10,000 x 2): 'Name' 'Value' i.e. dataset1= {'Name1', 2.32; 'Name2', 3.42}
Dataset 2 (5000 x 2): 'Gene' 'Name,Name' i.,e. dataset2 = {'Gene1', []; 'Gene2', 'Name1'; 'Gene3', 'Name2 // Name3'}
My solution to this was to split by separator.
for j=[2 3 4 5 6] %dataset2 actually has multiple columns of significance that need splitting, but not important now
for i=1:length(a)
if isempty(a{i,j}) == 1
continue
end
b = char(a{i,j});
c = strsplit(b,' // ');
a{i,j} = [c];
end
end
This converted cells with multiple promoter names into a cell array with promoter names (i.e. {'Gene' 1x3} where the 1x3 is = {'Name1' 'Name2' 'Name3'}.
My solution to merge the data was to use a for loop that assesses the size of that 1x3 cell (that could just be a single name), and search dataset1 for the associated name and append the associated value to dataset 2 in a manner such as:
Dataset 2: {'Gene1', 2x3} where the 2x3 = {'Name1', 'Name2', 'Name3'; 'Value1', Value2', 'Value3'}
Here is my code, I tried to annotate it to make it easier to follow:
for i=1:length(dataset2)
if isempty(dataset2{i,5}) == 1 % 0 'Names' associated w/ gene
continue
end
s = size(a{i,5});
if s(1,2) == 1 % One 'Name' associated w/ gene
x = a{i,5};
for j=1:length(dataset1)
y = dataset1{j,1};
if strcmp(x,y) == 1 % Using strcmp to find matching 'Names'
a{i,7} = dataset1{j,3};
a{i,8} = dataset1{j,4};
end
end
end
if s(1,2) > 1 % Multiple 'Names' associated with gene
r = a{i,5};
p = 1;
for rr=1:length(s(1,2))
x = r(1,rr);
for m=1:length(dataset1)
y = dataset1{m,1};
if strcmp(x,y) == 1
a{i,7}(2,rr) = dataset1{j,3};
a{i,8}(3,rr) = dataset1{j,4};
end
end
end
end
end
I'm sure this is a very convulted script, so any insight would be appreciated.Jack Crowhttps://uk.mathworks.com/matlabcentral/profile/authors/13677523-jack-crowtag:uk.mathworks.com,2005:Question/4455562019-02-18T11:57:50Z2019-02-18T16:57:57ZCenter text on screenVery basic question, but how can I (exactly) center text on screen (or figure window)?
If I just use
text(.5,.5,'x'); axis off
the x is not centered on screen.Tobias Johanssonhttps://uk.mathworks.com/matlabcentral/profile/authors/4299594-tobias-johanssontag:uk.mathworks.com,2005:Question/2285572015-07-06T07:40:42Z2019-02-18T16:51:48ZExperts of MATLAB, how did you learn? Any advice for beginner/intermediate users?The community is very helpful, yet I feel really powerless that I cannot find the appropriate way to code, nor find the problems with the codes I have written. I have read numerous books on MATLAB, mostly related with science and engineering applications.
Any advice to improve would be greatly appreciated.
Thanks.mor davehttps://uk.mathworks.com/matlabcentral/profile/authors/4500990-mor-davetag:uk.mathworks.com,2005:Question/4456142019-02-18T16:35:35Z2019-02-18T16:44:20ZHow do I extract a function calculated and used inside my ode45 function?Hello,
I'm using ode45 to produce solutions to ODE's and It works. However, I have a function inside of the code that I want to do a graph in the main.m. The system is modelled with the following equations:
Well, the graph I want to do is and versus time. Do you have any ideas how to get them?
Thank you very much in advance
Ignacio Lópezhttps://uk.mathworks.com/matlabcentral/profile/authors/14814368-ignacio-lopeztag:uk.mathworks.com,2005:Question/4456092019-02-18T16:20:45Z2019-02-18T16:43:04ZHow to calculate sum of all the possible combinations of two vector elementsI have two vectors A and B with different lengths. The B vector always have 4 elements. How can I obtain the vector C containing sum of all the possible combinations of elements of B vector with A.
For example B= [1 2 3 4] and A= [0.1 0.2 0.3 0.4 0.5 0.6]
Then C= [1.1 1.2 1.3 1.4 1.5 1.6 2.1 2.2 2.3 2.4 2.5 2.6 3.1 3.2 3.3 3.4 3.5 3.6 4.1 4.2 4.3 4.4 4.5 4.6]
Thank youDavoudhttps://uk.mathworks.com/matlabcentral/profile/authors/3867523-davoudtag:uk.mathworks.com,2005:Question/4456152019-02-18T16:37:41Z2019-02-18T16:39:36ZCategorical to Numerals variablesHow I can deal with the categorical variables for multinomial logistic regression, SVM and ANN for a classification problem?
My response is a categorical variable (yes,no) and two of predictors are also categorical (red, green, black, blue and high, medium, low).Tanvir Kaisarhttps://uk.mathworks.com/matlabcentral/profile/authors/9167252-tanvir-kaisartag:uk.mathworks.com,2005:Question/4456002019-02-18T15:48:44Z2019-02-18T16:28:26ZWarning: Matrix is singular, close to singular or badly scaled. Results may be inaccurate. RCOND = NaN. I have coding such as this:
En = length(n); % n = number of data tottaly
Ex1= sum(x1); % Ex1= number of Depth
Ex2= sum(x2); % Ex2= number of Amax
Ex3= sum(x3); % Ex3= number of Mw
Ex4= sum(x4); % Ex4= number of Vs
Ex5= sum(x5); % Ex5= number of Distance
x1x2= dot(x1,x2);
x1x3= dot(x1,x3);
x1x4= dot(x1,x4);
x1x5= dot(x1,x5);
Ex1x2=sum(x1x2);
Ex1x3=sum(x1x3);
Ex1x4=sum(x1x4);
Ex1x5=sum(x1x5);
x1_2 = x1.^2;
x2_2 = x2.^2;
x3_2 = x3.^2;
x4_2 = x4.^2;
x5_2 = x5.^2;
Ex1_2 = sum(x1_2);
Ex2_2 = sum(x2_2);
Ex3_2 = sum(x3_2);
Ex4_2 = sum(x4_2);
Ex5_2 = sum(x5_2);
Ey1=sum(y1);
x1_y1=dot(x1,y1);
x2_y1=dot(x2,y1);
x3_y1=dot(x3,y1);
x4_y1=dot(x4,y1);
x5_y1=dot(x5,y1);
Ex1_y1=sum(x1_y1); %Ex1_y = number x1 multiplyied y
Ex2_y1=sum(x2_y1); %Ex2_y = number of x2 multiplied by y
Ex3_y1=sum(x3_y1);
Ex4_y1=sum(x4_y1);
Ex5_y1=sum(x5_y1);
A = [En Ex1 Ex2 Ex3 Ex4 Ex5;Ex1 Ex1_2 Ex1x2 Ex1x3 Ex1x4 Ex1x5;Ex2 Ex2_2 Ex1x2 Ex1x3 Ex1x4 Ex1x5;...
Ex3 Ex3_2 Ex1x2 Ex1x3 Ex1x4 Ex1x5;Ex4 Ex4_2 Ex1x2 Ex1x3 Ex1x4 Ex1x5;Ex5 Ex5_2 Ex1x2 Ex1x3 Ex1x4 Ex1x5];
At = A';
G = [Ey1;Ex1_y1;Ex2_y1;Ex3_y1;Ex4_y1;Ex5_y1];
Ai = inv(At);
I want to make an inversion task but, I got the massage like this "Warning: Matrix is singular, close to singular or badly scaled. Results may be inaccurate. RCOND = NaN"
Is there any one can help me to slove my probelm?
ThxAkhmad Muktafhttps://uk.mathworks.com/matlabcentral/profile/authors/7503568-akhmad-muktaftag:uk.mathworks.com,2005:Question/4455272019-02-18T08:36:28Z2019-02-18T16:26:17ZDetect all the rectangles in imageHey all,
in the following image, all the rectangles are a little bit deformed due to power leakage effect. I want to detect all the rectangles and obtain the positions of the rectangles.
Is there a way to detect all rectangles?
Thank yousimon xuhttps://uk.mathworks.com/matlabcentral/profile/authors/14242564-simon-xutag:uk.mathworks.com,2005:Question/4455402019-02-18T10:30:53Z2019-02-18T16:23:47ZMultiple Angle Measurement from Image
Hi, I am trying to measure the angle between all the carbon tows (angle between the red lines). I have processed the image several times, reducing it to gray scale, then applying the Hough Peaks function to make it more uniform. I have the function to measure one angle at a time. Can I measure all the angles at once in this image ? I will be grateful for any suggestion or advice.Mayank Gautamhttps://uk.mathworks.com/matlabcentral/profile/authors/14811655-mayank-gautamtag:uk.mathworks.com,2005:Question/4456112019-02-18T16:23:29Z2019-02-18T16:23:29ZProblem of integration, the code run but the solution is not satisfying Hi all! I coded the Eq.C.4 to find η(t) and the code works, but, as you can see from the fig. attached, my solution does not match with the one proposed by a scientific paper for the same equation and input data. Any suggestions?
Roi=916;
Row=1024;
R=Row/Roi;
r=50;
d=50;
%column geometry
H0=50;
l=5;
b=5;
a=(2*l*H0/pi)^0.5;
Area=pi*a^2;
Vol=Area*H0;
%Dinamic of the block
Omega=1;
va=(3*(pi)^(3/2))/(16*sqrt(2))*(Omega*sqrt(l*H0))/(1+pi/4*R*(l/b));
%Surfaceelevation
E=zeros(1,301);
t=0:0.1:30;
for i=1:301
O=@(x,y)(besselj(0,x.*y.*a/d)).*((1-y.^2).^0.5).*y.*besselj(0,x*r/d).*((x.*tanh(x)).^0.5).*sin((((9.81/d*t(i).^2).*x).*tanh(x)).^0.5).*x;
E(i)=integral2(O,0,2000,0,1,'Method','iterated','AbsTol',1e-10,'RelTol',1e-10)
end
E1=-2*(a.^3)/(d^3.5)/(9.81^0.5)*va*d*E;Tommaso Attilihttps://uk.mathworks.com/matlabcentral/profile/authors/14259428-tommaso-attilitag:uk.mathworks.com,2005:Question/4456102019-02-18T16:22:15Z2019-02-18T16:22:15ZInterpolate positions between 2 matrixHello,
If you see the picture below, I am representing dinamically the blue point with a matrix and imagesc function. What I would like to do is filling the gap bewteen points with more points, so the final graph woould look like a line.
An example how I am plotting the graph
% First point position in the matrix
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
% Next time period the matrix will have other values for the second "blue" point
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 1 0
% I would like to get automatically a matrix that interpolate between both "1" values and get something like below to draw a line,
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
I hope to make myself clear,
Thanks in advance!Jose Martinezhttps://uk.mathworks.com/matlabcentral/profile/authors/14251386-jose-martinez