https://uk.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2020-07-16T15:08:35Ztag:uk.mathworks.com,2005:Question/5659642020-07-16T11:17:00Z2020-07-16T15:07:39Zcalculate sum over nHello! I try to calculate a sum over n of matrices K,L such as K(m,n)*L(n,t)*L(n,j). So far I have the code below, but I am doubing I wrote it correctly. Could you please give advise on that?
K=rand(20,20);
Ln=rand(20,20);
sum11=zeros(1,20);
for n=1:20
summ=K(:,n).*Ln(n,:).*Ln(n,:);
sum11(n)=sum11(n)+summ;
endBen Anderssonhttps://uk.mathworks.com/matlabcentral/profile/authors/4973221tag:uk.mathworks.com,2005:Question/5660932020-07-16T15:07:38Z2020-07-16T15:07:38ZInstall matlab 2020a problem ubuntu abortedHi, I have been trying to install matlab 2020a in ubuntu 18.04 with no success. After calling the sudo ./install option the installer doesn't even apper and the only message I get is:
Exception in thread "main" java.lang.NoClassDefFoundError: com/mathworks/laisserver/api/LaisServer
Caused by: java.lang.ClassNotFoundException: com.mathworks.laisserver.api.LaisServer
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
terminate called after throwing an instance of 'JailContainerException'
what(): Error: 63: Connector couldn't start
Aborted
The java version the computer is running is:
openjdk version "11.0.7" 2020-04-14
So far, I haven't been able to find a solution/ uderstand this error. Paolo Cachihttps://uk.mathworks.com/matlabcentral/profile/authors/15578656tag:uk.mathworks.com,2005:Question/5660902020-07-16T15:05:14Z2020-07-16T15:07:37ZI WANT TO KNOW WHY SO MUCH "." (dot) to define a statement, and does it mean something. Swarm.Particles(k).X ??? for k = 1 : noP
Swarm.Particles(k).X = (ub - lb) .* rand(1,nVar) + lb;
Swarm.Particles(k).V = zeros(1,nVar);
Swarm.Particles(k).PBEST.X = zeros(1, nVar);
Swarm.Particles(k).PBEST.O = inf; % for minimization
end
*** Here they are storing the values in an array; noP = 300; nVar=10***** RAJESH Rhttps://uk.mathworks.com/matlabcentral/profile/authors/16272198tag:uk.mathworks.com,2005:Question/5660572020-07-16T14:03:46Z2020-07-16T15:06:08ZConnecting Dots in a plotHello everyone!
I have 1 Vector (8x1 dimension) and 1 Array (3x1x8 dimension) and I want to connect each number of the vector with first element of each vector that belong to the array (this would mean 1x1x8)
My script works but I am struggling to connect the each point with a line, Can you help me ?
Here is my extract of code:
for i = 1:Nplies
zbar(i,1) = -(h + t)/2 + i*t;
theta = thetadb(i) * pi / 180;% ply i angle in radians, from bottom
theta_global(i,1) = thetadb(i);
c = cos(theta);
s = sin(theta);
T = [ c^2 s^2 -2*c*s; s^2 c^2 2*c*s; c*s -c*s (c^2 - s^2)];
T_inv = [c^2 s^2 c*s; s^2 c^2 -c*s; -2*c*s 2*c*s (c^2 - s^2)];
Qbar = T * Q * T_inv; %transformed reduced stiffness matrix
NT(:,:,i) = NTi + Qbar * abar * t * deltaT;
NT_plot(:,:,i) = NTi + Qbar * abar * t * deltaT;
figure(2)
plot (NT_plot(1,:,i),zbar(i,1),'dr')
xlabel('Loads in X')
ylabel ('Laminate Global Thickness [mm]')
legend ('NT across the Laminate')
hold on
grid on
line(NT_plot(1,:,i),zbar(i,1))
endMarcelo Boldthttps://uk.mathworks.com/matlabcentral/profile/authors/13894931tag:uk.mathworks.com,2005:Question/5660872020-07-16T15:04:40Z2020-07-16T15:06:07ZFind string corresponding to another string within a text fileHi,
I have a text file,
I was trying to read the latitide, longitude and station name corresponding to the associated strings within a text file. For example for reading the latitude and longitude in the file, the below lines worked.
buffer = fileread(fullFileName) ;
lat=str2double(regexpi(buffer, '(?<=Station latitude:\s+) [\d\.]+', 'match'));
lon=str2double(regexpi(buffer, '(?<=Station longitude:\s+) [\d\.]+', 'match'));
However, for station name which is in the .txt file (attached) as Station name: Payerne,
the below line did not work and I am getting NaN as output
name=str2double(regexpi(buffer, '(?<=Station name:\s+) \w*', 'match'));SChowhttps://uk.mathworks.com/matlabcentral/profile/authors/15757394tag:uk.mathworks.com,2005:Question/5646472020-07-14T05:48:48Z2020-07-16T15:03:54ZReportgenerator Template/Styles Matlab 2018bHello,
I am trying to include a Style template into my PDF report. When I create a section I use
- TemplateSrc, 'mytemplate'
as parameter.
For mytemplate I took the 'default PDF template' from the report generator GUI. To get it I did that:
Report Explorer (Generator) -> Edit Document Conversation Template -> Default PDF Template -> Copy Template
If I try to use it directly I get the error: Section 1 not found.
So i unzip the default template.pdftx and look into the html files. The only section I can find is:
<dptemplate name="rgSect1Title">
<h2 class="rgSect1Title" style="counter-increment:sect1; counter-reset:sect2">
<hole id="prefix" default-style-name="rgSect1TitlePrefix">prefix</hole>
<hole id="number" default-style-name="rgSect1TitleNumber">number</hole>
<hole id="text" default-style-name="rgSect1TitleText">title</hole>
</h2>
</dptemplate>
So I renamed my section to sect with
- TemplateName, 'Sect'
and after that did not work I tried to rename the Sect in the html file to Section. Nothing worked so far. If I set it to Section1 I can generate the report but the Section1 does not show. Maybe the hole ids, styles or what so ever is not set correctly.
So I am wondering how I can create a style with Matlab 2018b for counting up SectionsX within the template correctly.
Thanks a lot
Martin
Martin Meiboomhttps://uk.mathworks.com/matlabcentral/profile/authors/14654092tag:uk.mathworks.com,2005:Question/5617312020-07-08T15:32:37Z2020-07-16T15:03:37Zhow can I direct entities on simevent basing myself on probability?Hello!
I am just approaching Simevents and I am trying to understand how, after an entity has passed through an entity server, I can split the flow and redirect entities based on a probability that I will assing.
I hope my question is comprehensible.
Thanks in advanceIlaria Shireen Sestilihttps://uk.mathworks.com/matlabcentral/profile/authors/18065445tag:uk.mathworks.com,2005:Question/5660752020-07-16T14:41:53Z2020-07-16T15:03:29ZFinding minimums and maximums of repetitive numbers in a matrixHello,
Would you please assist me to find minimums and maximums of repetitive numbers in the attached matrix (EXCEL file). Actually, corresponding values of red ovals and green and blue arrows are different events recorded as biomechanical data during human gait. I am a beginner and need explanation to understand how to calculate the corresponding values. Thank you very much.
Vahid Esmaeilihttps://uk.mathworks.com/matlabcentral/profile/authors/18578510tag:uk.mathworks.com,2005:Question/5629372020-07-10T15:37:15Z2020-07-16T15:02:27ZMobile Robotics Simulator inquiryI am now learning mobile robots control algorithms and want to know if there an efficient simulator that can run simulink models. I don't want third party simulator, rather I want a basic one for differential drive robots that can enable me from running my algorithms that built I from scratch. Ammar Tahahttps://uk.mathworks.com/matlabcentral/profile/authors/11183776tag:uk.mathworks.com,2005:Question/5660722020-07-16T14:38:55Z2020-07-16T14:59:17ZImport multiple files and plot data.Hi,
I am trying to write a script capable of opening all files from within the same folder.
Each file has two columns coordinated (X, Y) in .ASC-II format.
After importing all the files in the same folder, I need to plot all the graphics separately.
The script I wrote is opening the correct number of files and also naming them correctly, however the 47 cells of myData have the values of the first file, as if it was copying 47 times the file “run_01”.
Could anyone suggest how to overcome this problem?
Thanks
-----
% Import data
run = importfile("D:\Desktop\Teste\run_01", [1, inf]); % describe the direction of the files.
numFiles = 47; % number of files you want to open (they must be inside the same folder)
startRow = 2; % The loop starts from the second file
endRow = inf;
myData = cell(numFiles,1);
for fileNum = 1:numFiles
fileName = sprintf('run_%02d',fileNum);
myData{fileNum} = importfile("D:\Desktop\Teste\run_01",[startRow,endRow]);
end
% To remove NaN cells
for fileNum = 1:numFiles
fileName = sprintf('run_%02d',fileNum);
myData{fileNum, 1} ([1:2,1003:end],:) = [];
end
% plot
figure
for i = 1:length(myData)
plot(myData{i,1}) ;
endRafael Brognoli Reccohttps://uk.mathworks.com/matlabcentral/profile/authors/18569709tag:uk.mathworks.com,2005:Question/5634892020-07-11T21:43:33Z2020-07-16T14:57:01ZTools used for Sparse Matrix EfficiencyI have read documentation and the MATLAB community answers regarding this and I found a lot of helpful information about the power of sparse matrices, I just need help applying it to my sceanrio as this is the first time I am working with them.
I currently have a 22,400 x 22,400 sparse identity matrix that I created with speye(n) where n= 24,000. In a loop I have multiple element assignments that I do which iterates n number of times. The total run time for this code is 13.811054 seconds which is very poor considering this being a placeholder, and I plan on running 10e6 x 10e6 size matrices and I appreciate pointers to have more efficient code.
I ran multiple trials with on how the size affects my speed, along with time it took I calculated how much elements were allocated to the matrix (non-zero elements and I tabulated 3 readings below.
Size Time elapsed Allocation
576 x 576 0.128121 seconds 1.042%
2,800 x 2,800 0.657801 seconds 0.2143%
22,400 x 22,400 13.811054 seconds 0.0268%
The skeleton of my code is shown below;
A = -6.*speye(n); %intializaiton of a nxn sparse matrix
for ix = 1:X
for iy = 1:Y
for iz = 1:Z
%multiple calculations and conditional statements
A(icent,ixp)=1;
A(icent,iyp)=1;
A(icent,izp)=1;
A(icent,ixm)=1;
A(icent,iym)=1;
A(icent,izm)=1;
%allocations to the sparse matrix (poorly done)
end
end
end
l wish to know what is the best to improve the efficency of this, I understand how clunky and inefficent my element allocation is and I want to improve it, any pointers are appreciated.
While I was reading answers on MATLAB, I came across John D'Errico's Answer to a similar question which dealt with using spalloc, which was well-worded, however I can't seem to understand how to apply spalloc() to my sceanrio where I already require a declared sparse identity matrix.
I hope to have an efficient code to run large matrix sizes, appreciate the help in advance.
**Edit - the 1s can be allocated only inside the nested loop as there are prior calculations that need to be done, I realize John D'Errico's Answer mentions in the beginning - In general, DON'T DO IT! That is, don't build a sparse matrix one element at a time. Even if you use spalloc, the matrix will be inefficient to build.
Edit - I am working with a symmetric banded matrix, the spine of it will be the speye() identity matrixHans123https://uk.mathworks.com/matlabcentral/profile/authors/11890683tag:uk.mathworks.com,2005:Question/5660002020-07-16T12:00:09Z2020-07-16T14:56:43ZSolve large linear systems with Parallel computing toolboxDear all,
I need to solve something of this form , where are just 7 distinct doubles and I is the identity matrix. Of course, those linear systems can be solved in parallel, and I want to do that in Matlab with the PCT. The matrix is A = gallery('poisson',n).
In my cluster, I have a node with 16 CPUs, and I want to use this fact to boost the performance. I wrote the following code to see if the parfor gives an improvement w.r.t the classical for. I started a parallel pool of 7 workers, and when I run it on the cluster I specified to use 7 CPU cores, according to the phylosophy "1 worker per CPU core", but my performance does not get better.
Here's the code with the following output:
clear all
close all
m = 70^2;
A = gallery('poisson',70);
I = speye(m);
v = ones(m,1);
x = zeros(m,7);
theta = [1.1,0.2,5.6,0.2,6,8,9.9];
tic
for i=1:7
x(:,i) = (A - theta(i)*I)\v;
end
toc
parpool(7)
tic
parfor i=1:7
x(:,i) = (A - theta(i)*I)\v;
end
toc
The results are:
Elapsed time is 0.184104 seconds. (with for loop)
Elapsed time is 0.451166 seconds. (with parfor loop)
So my questions are:
is there something wrong in how I wrote my code to run in parallel? How can I improve my performance? (iterative solvers, or differen methods)
why the parfor considerably slower than the classical for? I've seen that linear algebra operations are already multithreaded and hence there could be no gain with a parforGiuliaChttps://uk.mathworks.com/matlabcentral/profile/authors/13538196tag:uk.mathworks.com,2005:Question/5656402020-07-15T20:21:23Z2020-07-16T14:54:32ZHow to change Y-axis in histfit plot from counts to percents?Dear All,
I have next plot :
h= histfit(myVec);
set(gca, 'XLim', [-2 2]);
ylim([0 400]);
set(h(2),'color','black');
How I can change this plot to plot with Y-axis in percentages not in counts ?
Thanks so much inadvance!IMhttps://uk.mathworks.com/matlabcentral/profile/authors/13970971tag:uk.mathworks.com,2005:Question/5660212020-07-16T12:55:39Z2020-07-16T15:08:35ZArray dimensions not agreeingI'm trying to calculate the magnetic field of a stack of magnet rings given the dimensions of the magnets. However, when I try to calculate the field for each of the parameters for the ring dimensions, the array dimensions of the magnetic field do not agree, giving the error "Array dimensions must match for binary array op.".
I think there is an issue with the way I am combining the arrays in the equation for Bz (see below).
%Range of axial field and step size for functions
zmin=-1;
zmax=1;
dz=0.01; % step size for the plots
nz=round((zmax-zmin)/dz)+1; %number of z steps in the limit
iz=1:nz; %index for each z step
z(iz)=linspace(zmin,zmax,nz); %values of z
%Structure for a magnet, defining the length of a magnet, the
%length of the stack and the position of each magnet (everthing to
%calculate the B field)
B0=1.4; % saturation of permanent magnetic material
nmag=10; % number of rings
imag=1:nmag; %ring index
zlength=(zmax-zmin)/nmag; %length of ring
zstart(imag)=zmin:zlength:(zmax-zlength); %position of ring edge with lower z value
zend(imag)=zstart+zlength; % set up a vector with the ends of each ring section
zmag(imag)=-0.9:0.2:0.9;
%five optimisation parameters
ia=1:5;
a(ia)=linspace(-0.2,0,ia(end));
ib=1:5;
b(ib)=linspace(-0.1,0.1,ib(end));
ic=1:5;
c(ic)=linspace(-0.1,0.1,ic(end));
id=1:5;
d(id)=linspace(-0.1,0.1,id(end));
ie=1:5;
e(ie)=linspace(-0.1,0.1,ie(end));
%magnet radii
or=zeros(imag(end),ia(end),ib(end));
for ib = 1:ib(end)
or(:,:,ib) = 1 + zmag'.^2*a + b(ib)*zmag'.^4;
end
ir=zeros(imag(end),ic(end),id(end),ie(end));
for id = 1:id(end)
for ie = 1:ie(end)
ir(:,:,id,ie) = c + d(id)*zmag'.^2 + e(ie)*zmag'.^4;
end
end
Bz=zeros(nz,nmag,ia(end),ib(end),ic(end),id(end),ie(end)); % store the B field for each ring separately in Bz
for imag=1:imag(end)
Bz=Bz+(B0*0.5*( (zend(imag)-z')./sqrt((zend(imag)-z').^2+ir(imag,:,:,:).^2/4) ...
-(zstart(imag)-z')./sqrt((zstart(imag)-z').^2+ir(imag,:,:,:).^2/4) ...
-(zend(imag)-z')./sqrt((zend(imag)-z').^2+or(imag,:,:).^2/4) ...
+(zstart(imag)-z')./sqrt((zstart(imag)-z').^2+or(imag,:,:).^2/4) ));
endJChttps://uk.mathworks.com/matlabcentral/profile/authors/13774303tag:uk.mathworks.com,2005:Question/5660842020-07-16T14:50:05Z2020-07-16T14:50:05Zconverting txt to xlsxHi I am trying to convert a textfile to xlsx. file
My textfile holds this information:
StudentName: James
School: University of Blah
Year: 2020
Grade: 3
Pin: 40
And I want to convert this to xlsx. file
*check the attached screenshot file*
hjohttps://uk.mathworks.com/matlabcentral/profile/authors/15220266tag:uk.mathworks.com,2005:Question/5656222020-07-15T19:53:01Z2020-07-16T14:49:40ZFormatting fread binary file (converting from FORTRAN script)I am converting some Fortran to MATLAB and am stuck early on when trying to load a binary file. I know MATLAB well but I have not had much experience loading binary files. I have mostly had to only load text files in the past. Furthermore, I am a newbie to Fortran and the I/O commands and generally lower-level language is a challenge.
The Fortran script has a read statement:
READ(Ifile,FMT='(A70)',ERR=993) Tag
My understanding is that this command has a file id (Ifile) similar to "fid" which has been called using a previous OPEN command (similar to fopen).
Furthermore, the '(A70)' specifies that the read command should read 70 bytes of the file as a character (A).
The result is stored in the variable "Tag".
However, in MATLAB, if I use
Tag = fread(fid,70,'char')
I don't get the same result as Fortran.
What am I missing here? Any help is appreciated.Darcy Cordellhttps://uk.mathworks.com/matlabcentral/profile/authors/6864376tag:uk.mathworks.com,2005:Question/5656882020-07-15T21:32:39Z2020-07-16T14:47:48ZMatlab shrinking subplot graphs when running the codeEverytime I run my code, the graphs I have end up shrinking.
This is my code:
figure(100);clf;
or = [0.8500, 0.3250, 0.0980];
ye = [0.9290, 0.6940, 0.1250];
bl = [0, 0.4470, 0.7410];
vec = [or;ye;bl];
clr = 'rgb';
sz = 14;
yname(1).s = '\mu_s [cm^{-1}]';ytitle(1).s = 'Scattering';
yname(2).s = 'g [-]';ytitle(2).s = 'Anisiotropy';
yname(3).s = '\mu_s'' [cm^{-1}]';ytitle(3).s = 'Reduced Scattering';
ymax = [3000 1 400];
for k=1:3
subplot(3,1,k)
for j=1:length(diadia)
plot(lambdalambda, musgp(:,j,k),'-','color',vec(j,:),'linewidth',1)
hold on
y = ymax(k); dy = y/10; x = mean(lambdalambda);
text(x,y-dy*j,sprintf('dia = %0.3f um', diadia(j)), ...
'fontsize',sz, 'color',vec(j,:))
end%j
set(gca,'fontsize',sz)
xlabel('wavelength \lambda [\mum]')
ylabel(yname(k).s)
title(ytitle(k).s, 'fontsize',14)
end%k
is there a way I can make it so it does not shrink, or how would I separate the figure into three plots if this is not possible?Rachel Fetterhttps://uk.mathworks.com/matlabcentral/profile/authors/18761237tag:uk.mathworks.com,2005:Question/5656102020-07-15T19:31:01Z2020-07-16T14:46:31ZError using textscan Invalid file identifier. Use fopen to generate a valid file identifier.I'm doing a simulation using MATLAB. There is a python code that reads the plain-text files for model setup and generates text files easy to import by Matlab. The program makes plain-text files containing number of values and a column of values. However, when I run the program in MATLAB the following error occurs:
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in load_setup>load_word (line 247)
temp=textscan(fid,'%d'); % eat up default '1'
Error in load_setup (line 59)
Model.code=load_word(standard_folder_name,'Model_code');
Error in Simulate (line 57)
[conditions, modes, Model]=load_setup(setup_name, model_name);
I don't know exactly what to do.Ashkan Shahsavanhttps://uk.mathworks.com/matlabcentral/profile/authors/18983362tag:uk.mathworks.com,2005:Question/1237592014-03-30T20:49:34Z2020-07-16T14:46:18ZResetting Pop up MenuI just ran accross an annoying issue with pop-ups in GUIs. If you
create a list of items in a popup, then change the 'String' property
to
display a new shorter list, you must reset the 'Value' property
(which
points to the string in the list to display) manually. If you don't,
and the Value property is no longer valid, an annoying error occurs
which is not covered well in the help. For example, if old list had
5
items with Item # 5 selected, Value = 5. Now if you set the String
property to a 3 element array, Value is not automatically reset and
now
exceeds the range of the string array. The control will not be drawn
and a cryptic error message 'Value must be set to a valid string
integer...' or something like that is displayed. Very annoying. I
couldn't find a reference to this in the on-line or website help.
Adedejihttps://uk.mathworks.com/matlabcentral/profile/authors/2874792tag:uk.mathworks.com,2005:Question/5660812020-07-16T14:45:42Z2020-07-16T14:45:42ZHow to import an image in a programmatic UI from scratch?I work on image processing and I can't find sources to learn programmatic UI without using guide or App Designer.
Stephani Kangahttps://uk.mathworks.com/matlabcentral/profile/authors/18629889tag:uk.mathworks.com,2005:Question/5637112020-07-12T13:32:03Z2020-07-16T14:44:11ZWhen does randomness enter a shuffled "deck" of coin tosses.%shuffle a clean deck of 1e6 tails and heads
p=ones(1,500000); m=-ones(1,500000);C=[p ; m];a=C(:)';
%1st shuffle
A=a(1:500000);B=a(500001:1e6);C=[A ; B];C1=C(:)';
% next 1e3 shuffles
A=C1(1:5e5);B=C1(5e5+1:1e6);C=[A;B];C2=C(:)';
A=C2(1:5e5);B=C2(5e5+1:1e6);C=[A;B];C3=C(:)';
A=C3(1:5e5);B=C3(5e5+1:1e6);C=[A;B];C4=C(:)';
...
Brainlock :
How to use output of a command as input in following repeated commandsgeorge simpsonhttps://uk.mathworks.com/matlabcentral/profile/authors/16929055tag:uk.mathworks.com,2005:Question/5660782020-07-16T14:43:59Z2020-07-16T14:43:59ZModifying Read Only ID of CAN messageI'm using a network of multiple sensors that I want to configure over CAN. Each Sensor has an ID from 0-7.
I currently use a CAN-database to create the Config-message. The default config message identifier is 0x200. The identifier gets changed based on the sensor I want to configure like this:
message-ID = 0x200 + sensorID*0x10
So the config message for sensor 0 has ID 0x200, sensor 1 0x210, sensor 2 0x220 and so on. The same is true for all other messages that can be sent.
The easiest solution for me would be to modify the message-ID from the default message (ID 0x200) like I'm already doing it with the signals:
msgRadarCfg = canMessage(dbc,'RadarCfg');
msgRadarCfg.Signals.RadarCfg_SensorID = sensorID;
Message.ID however is read-only, so this doesn't work:
msgRadarCfg.ID = msgRadarCfg.ID + sensorID*16;
Is there another way to change the message ID without me either modifying the dbc-file to include all messages for all sensor-IDs or building the messages "by hand"?Maximilian Kochhttps://uk.mathworks.com/matlabcentral/profile/authors/14552811tag:uk.mathworks.com,2005:Question/665722013-03-10T10:42:16Z2020-07-16T14:41:58Zconverting video to frames [f,p]=uigetfile( {'*.avi','AVI Video files (*.avi)';'Select an AVI format video','input\'});
Frames=mmreader([p,f]);
get(Frames);
nFrames = Frames.NumberOfFrames;
pickind='jpg';
for k = 1:nFrames
% mov(k).cdata = read(Frames, k);
a=read( Frames,k);
%%%%% SOME OPERATION
strtemp=strcat('E:\K1frames\',int2str(k),'.',pickind);
imwrite(a,strtemp);
end
FRAMES TO VIDEO
t=length(dirlist);
for xc = 1:length(dirlist)
xb = imread([pathname,dirlist(xc).name]);
figure,imshow(a),title('load frames');
Fx(:,xc)=getframe;
end
implay(Fx,84) %84 FRAMES
NOW HOW TO CONVERT THIS VIDEO INTO FRAMES AGAINnkumarhttps://uk.mathworks.com/matlabcentral/profile/authors/3941207tag:uk.mathworks.com,2005:Question/5660632020-07-16T14:17:27Z2020-07-16T14:40:32Z1) Speed up gctest function and 2) error when I have a large number of lags in gctestHi all,
I have two problems related to the build in gctest function in Matlab.
1) I am trying to perform a Ganger causality test in a series of time-series. The problem is that since I have a lot of time-series to test it actually takes forever. More precisely I have more than 200 and it takes more than 3 minutes for one year. Since, I want to test it for 36*6 years the total amount of time goes up to 10 hours!
My code looks likes this
parfor j = 1:noIns
sample = setdiff(1:noIns,j);
[h1{j}, pvalue1{j}, stat1{j}, cvalue1{j}] = arrayfun( @(i) gctest( ret(:,j), ret(:,i),...
'Alpha', alpha, 'NumLags', numLags, 'Test', test), sample, 'UniformOutput', true);
end
Any ideas how I can speed this up?
2) Also, I have a second question. When I increase the number of lags, the gctest gives an error (Matrix must be positive definite). This is strange since using the same data and number of lags in R or Eviews the Granger Causality test runs properly.
Thank you in advance for you time!
Elrichttps://uk.mathworks.com/matlabcentral/profile/authors/1113837tag:uk.mathworks.com,2005:Question/5660692020-07-16T14:28:13Z2020-07-16T14:40:03ZHow to hold True value infiniteI have a variable that will be false, true, then false. I want to home onto the true value on a second variable until the end of the simulation.
For example the window is clean, until I touch it. I have a Boolean variable if I’m touching the glass. But I want to capture the window and it’s now forever smudge. Rebecca Redhttps://uk.mathworks.com/matlabcentral/profile/authors/6993269tag:uk.mathworks.com,2005:Question/5660242020-07-16T12:59:43Z2020-07-16T14:39:48ZRenaming headers in TableHi,
I want to make a table from an array by using the array2table function. This works perfectly fine for my datasets whereby table headers do not match. But on occassion I have it whereby the data will have headers that are the same. I.e.
'ground_force_px' 'ground_force_py' 'ground_force_pz' 'ground_force_vx' 'ground_force_vy' 'ground_force_vz'
'ground_force_px' 'ground_force_py' 'ground_force_pz' 'ground_force_vx' 'ground_force_vy' 'ground_force_vz'
Is there a way whereby I can to convert from array2table whilst keeping these header names the same ?
Many thanks, Jake Bowdhttps://uk.mathworks.com/matlabcentral/profile/authors/12815077tag:uk.mathworks.com,2005:Question/5659942020-07-16T11:53:24Z2020-07-16T14:39:48Zcolor-coding a 2D contour of nozzle.Hello everyone. I hope you are doing well.
I have been working on developing the nozzle contour of the expansion duct in a supersonic nozzle for a rocket. I try to increase the mach no.(M) from 1 to any dersired output value at the right side exit. Please refer to the first image where i am only using 3 mesh lines (Characteristic lines) to draw the nozzle contour and i obtain 9 nodes(i.e. Points of intersection on characteristic lines). At each of these nodes my mach number increses slightly till it reaches a desired value at the output.Please refer to fig.2 for the variation of various parametres at the nodes. One of these parameter is the mach no. (M i.e the 6th column). Mach no. increases gradually.
I basically want to colorcode the nozzle 2-D graph shown here according to the increasing mach no.from left end to right. Please suggest me how can i do that. Thank you. Khalid Rafiqhttps://uk.mathworks.com/matlabcentral/profile/authors/18902206tag:uk.mathworks.com,2005:Question/5560092020-06-28T09:57:11Z2020-07-16T14:39:22ZChange User ID or Delete Thingspeak AccountHi, I am wondering if I can change my user id for ThingSpeak or I can delete the ThingSpeak account and register one? Thanks a lot.Kevin Lihttps://uk.mathworks.com/matlabcentral/profile/authors/16694038tag:uk.mathworks.com,2005:Question/5656132020-07-15T19:32:57Z2020-07-16T14:39:20ZHow to vectorize this for loopHey guys, I'm having trouble to vectorize my for loop. I'm basically getting the values of 4 columns and multiplying by the values of another matrix's column. Then storing them in another column of the first matrix
i = 1:length(Bundle);
Bundle(i+n,6) = (Bundle(i,1))*cost_bundle1 + (Bundle(i,2)*cost_bundle2) + ...
(Bundle(i,3)*cost_bundle3) + (Bundle(i,4)*cost_bundle4); %cost per account
Bundle(i+n,7) = seguranca*tax*((Bundle(i,1)*venda_bundle1) + (Bundle(i,2)*venda_bundle2) + ...
(Bundle(i,3)*venda_bundle3) + (Bundle(i,4)*venda_bundle4));%revenue per account
Caixa(i+n,1) = Bundle(i+n,6) + cost; %total cost
Caixa(i+n,2) = Bundle(i+n,7); %total revenue
Caixa(i+n,3) = (Caixa(i+n,2)- Caixa(i+n,1)); %profitEnzo Tessarohttps://uk.mathworks.com/matlabcentral/profile/authors/15778763tag:uk.mathworks.com,2005:Question/5660662020-07-16T14:27:04Z2020-07-16T14:35:30ZGet the numbers of rows where values changeHi,
I have an array of data, structured like this:
Latitude Longitude Height
23 54 7
23 54 3
23 54 8
23 55 4
23 55 2
24 54 0
24 54 1
24 55 2
24 55 7
How can I get the numbers of the rows where either Latitude or Longitude changes (so from the example above the output would be rows 3, 5 and 7)?Maja Zdulskahttps://uk.mathworks.com/matlabcentral/profile/authors/14081515tag:uk.mathworks.com,2005:Question/5658262020-07-16T06:14:22Z2020-07-16T14:32:35ZHow to replace a word with another word in a cell array (case insensitive)Hi I am trying to replace words found in a string with a given value (case insensitive)
str = 'lemon lemontea Lemongrass lime';
replaceword = 'lemon' %case insensitive
withthis = {'berry', 'apple', 'flower'};
Assume that we will be given with enough number of words to replace all the occurance of the word
I want to return this:
newstr = 'berry appletea flowergrass lime';
I tried to use strrep but it would replace for Lemon... hjohttps://uk.mathworks.com/matlabcentral/profile/authors/15220266tag:uk.mathworks.com,2005:Question/5659792020-07-16T11:36:02Z2020-07-16T14:21:09ZHow can I add title to plots before the loopThe problem with my code is it creates the titles, xlabel and ylabel 500 times each, so this makes the code slow to execute. Is there any way to put these outside the for loop (j=1:50) making titles, xlabel and ylabel to create only 10 times?
figure
for i=1:10
for j=1:50
subplot(2,1,1)
plot()
title(sprintf('%d',i))
drawnow
subplot(2,1,2)
plot()
xlabel('something')
ylabel('something else')
title(sprintf('%d',i))
drawnow
end
endMahmuthttps://uk.mathworks.com/matlabcentral/profile/authors/14903293tag:uk.mathworks.com,2005:Question/5660062020-07-16T12:13:13Z2020-07-16T14:20:45ZDeep Q Learning - define an adaptive critic learning rate?Hello,
at the moment i use Deep Q Learning for process planning and i would like to use an adaptive critic learning rate to speed up the training.
Is there any direct way (or workaround) to use a learning rate that lowers over the training process, e.g. depending on the number of epochs/steps, in DQL?
Thanks in advance and best wishes
Niklas
Niklas Reinischhttps://uk.mathworks.com/matlabcentral/profile/authors/15185557tag:uk.mathworks.com,2005:Question/5657722020-07-16T02:38:31Z2020-07-16T14:20:05ZHow can I change some time dependent parameter during solving system of differential equations?Hello! Help me, please, with this task, because i'm stuck on it.
I work with two functions: one contains a system of differential equations with a time parameter, and the second must to solve it. But I don’t understand how to combine these two functions for work properly. It is necessary, that the parameter r(u (t)) change at each step t, like some step function:
if (u >= -inf) & (u < 1/3) r = -1
elseif (u >= 1/3) & (u < 2/3) r = 0
elseif (u >= 2/3) & (u <= inf) r = 1
xn = rand is a vector N by length(u).
So I must to choose element r exactle at time t, but I don't no how to do this in ode45 with her changing step.
And I do this for every i string (one element of string for one time period t) in matrix xn. Then I calculate some function ft; modificate matrix xn (random), and repeat this process t times. Then I choose best min value of ft, vector u and terminal (last) string of integral xd. The result of ft --> 0. The main question how to connect time parameter u and t to solve this system.
Help please to reconstruct code. Thanks a lot.
function dx = equat(xn, i, tk, xd)
u = xn(i,p);
if (u >= -inf) & (u < 1/3)
r = -1;
elseif (u >= 1/3) & (u < 2/3)
r = 0;
elseif (u >= 2/3) & (u <= inf)
r = 1;
end
dx = zeros(4,1);
dx(1) = xd(2);
dx(2) = xd(1) * xd(3)^2 - (1/(xd(1)^2));
dx(3) = (-0.005*r - 2 * xd(2) * xd(3))/xd(1);
dx(4) = xd(3);
end
function [ft] = fitness(xn, N, options) % Function for fitness evaluation
s = [1 0 1 17.2];
for i = 1:N
[tk, xd] = ode45(@(tk,xd) equat(xn, i, tk, xd), [0:0.1:17.2], [1 0 1 0.785], options);
ft(i) = sum((xd(end,:) - s).^2);
end
endYura Ivanovhttps://uk.mathworks.com/matlabcentral/profile/authors/12122086tag:uk.mathworks.com,2005:Question/5660602020-07-16T14:16:09Z2020-07-16T14:16:09ZDifference between function of sim and predict in Neural network?Could anyone tell what is the difference between the function of sim and predict in the prediction of neural network? Thank you. Xin Yee Taihttps://uk.mathworks.com/matlabcentral/profile/authors/16805641tag:uk.mathworks.com,2005:Question/5417812020-06-04T01:40:55Z2020-07-16T14:12:29ZTranslation Matrix For Image Processing ConfusionHi,
Im quite confuse with the matrix translation use to translate image in 3D using homogenous coordinate. In Matlab the coordinat for tx and tx is at the bottom left
whereas there are a lot of example in the internet is at on the right corner and given with a very simple example from 2D conversion as in the image.
What is the difference or is it very similar?
Thanks
Zamani Zamani Md Sanihttps://uk.mathworks.com/matlabcentral/profile/authors/17939166tag:uk.mathworks.com,2005:Question/5657122020-07-15T22:29:06Z2020-07-16T14:08:01ZSimulink: is there a way to only run a block once a (non-zero) signal arrives to it?Hello world,
I'm doing some offline biosignal analysis on simulink. I pass an entire set of signals (e.g. 100 seconds of duration each) to Simulink and buffer them immediately (with buffer length corresponding to fs * 100 seconds). The idea is to perform a series of sequential signal processing operations on these 100-second frames rather than by considering each sample independently.
Let's say I have a signal processing block straight after this buffering. This processing block will essentially "run twice": the first time for the first 100 seconds where there is no signal (i.e there IS a "signal" but its a just a flat 0 line), and then the second time the next 100 seconds corresponding to the actual biosignals. Now this processing block includes a plot function and a send to workspace block. So what happens is that I'm plotting an empty plot and sending nonsense to the matlab workspace on the "first" time the preprocessing block is called.
So my question is: Is there any way to run a block ONLY when a buffered non-zero signal (which may also include SOME 0 elements)? Or, alternatively, is there any way to ensure these processing blocks only run when I'd like them to?
Thank you,
RafaelRafael Corderohttps://uk.mathworks.com/matlabcentral/profile/authors/18428627tag:uk.mathworks.com,2005:Question/5660512020-07-16T13:50:33Z2020-07-16T14:03:42ZIndexing array of symbolic variables dependent on timeI need to create variable number of symbolic variables and access each of them individually. It is necessary that they are time varying for purposes of calling diff.
So far I can see that a variable number can be created by
N = 5 % number of variables for example
syms x(t) [1,N]
But if one then tries to access the first element, x1(t), this results in
>> x(1)
ans =
[ x1(1), x2(1)]Morten Nissovhttps://uk.mathworks.com/matlabcentral/profile/authors/8733171tag:uk.mathworks.com,2005:Question/5660422020-07-16T13:40:42Z2020-07-16T14:02:35ZObtaining the standard normal z scoreIs there an easy way to obtain the standard normal z score with an upper tail probability of 0.05/2 or any number at handAhmed Abdullahttps://uk.mathworks.com/matlabcentral/profile/authors/15651567tag:uk.mathworks.com,2005:Question/5660542020-07-16T13:57:31Z2020-07-16T13:57:31Zwhy doesn't data cursor display date when I use candle for plotting High, Low, Close and Open prices?I use candle for plotting High, Low, Close and Open prices versus some dates but data cursor doesn't show dates. here is my codes.
HighPrices=ohlc(:,2);LowPrices=ohlc(:,3);
ClosePrices=ohlc(:,4);OpenPrices=ohlc(:,1);
figure(5)
candle(HighPrices,LowPrices,ClosePrices,OpenPrices,'b',dn,'yyyyMMdd')
grid on
grid minor
when I use data cursor to see the required date which is related to X axis it displays me an strange number which is 7.379e+5alireza ghaemihttps://uk.mathworks.com/matlabcentral/profile/authors/9215622tag:uk.mathworks.com,2005:Question/5648662020-07-14T13:06:21Z2020-07-16T13:55:13Zhow to discretize a nonlinear model using MatlabI have this continuous nonlinear system and I want to discretize it using Matlab
If anyone can help me? This is the differential equations of the system
This is the state space model according to the authors of the paper that I’m studying
I want to know how to insert it in m files and how to make it discrete .. any idea??F.Mhttps://uk.mathworks.com/matlabcentral/profile/authors/16937603tag:uk.mathworks.com,2005:Question/5660092020-07-16T12:15:27Z2020-07-16T13:54:53ZHow to correctly calculate the angle between two planes?I have 2 point cloud files from a buildings gable rooftop (.ply attached) and after fitting a plane to each and getting the normal vectors in plane model object I'd like to calculate the angle between these two, but the result is different depending on which point cloud is input first!
One time I get 2.68555450304481 and if I change the order of input I get 0.456276904837795 !!
What am I missing? Also if run the code a couple of more times I get some changes in fractions like 0.45xxx turns to 0.46xxx !!!
% input point cloud file gui
[FileName,PathName] = uigetfile({'*.pcd;*.ply;',...
'Point Cloud Files (*.pcd,*.ply)';
'*.pcd','Point Cloud library files (*.pcd)'; ...
'*.ply','Polygon Mesh Point Cloud files (*.ply)';
'*.*', 'All Files (*.*)'}, ...
'Select a Point Cloud File');
ptCloud=pcread([PathName,FileName]);
[FileName,PathName] = uigetfile({'*.pcd;*.ply;',...
'Point Cloud Files (*.pcd,*.ply)';
'*.pcd','Point Cloud library files (*.pcd)'; ...
'*.ply','Polygon Mesh Point Cloud files (*.ply)';
'*.*', 'All Files (*.*)'}, ...
'Select a Point Cloud File');
ptCloud2=pcread([PathName,FileName]);
maxDistance = 0.02;
[model1,inlierIndices1,outlierIndices1] = pcfitplane(ptCloud,maxDistance);
[model2,inlierIndices2,outlierIndices2] = pcfitplane(ptCloud2,maxDistance);
% calculate the angle between two planes
angle = atan2(norm(cross(model1.Normal,model2.Normal)),dot(model1.Normal,model2.Normal));
% another method but the same results!!!
A1 = model1.Parameters(1);B1 = model1.Parameters(2);C1 = model1.Parameters(3);
A2 = model2.Parameters(1);B2 = model2.Parameters(2);C2 = model2.Parameters(3);
dotproduct = (A1*A2) + (B1*B2) + (C1*C2);
angle2 = acos(dotproduct);Alihttps://uk.mathworks.com/matlabcentral/profile/authors/18577246tag:uk.mathworks.com,2005:Question/5658112020-07-16T05:38:30Z2020-07-16T13:54:47ZHi why convert to 8 graylevel when processing for GLCM altough my data is 256 bitsPlease tell me about this subject clearlyFurkan bhttps://uk.mathworks.com/matlabcentral/profile/authors/18783061tag:uk.mathworks.com,2005:Question/1076132013-11-26T13:09:30Z2020-07-16T13:53:53ZPlease send the MATLAB code for simulation for an underwater free-space optical communication systemPlease send the MATLAB code for simulation for an underwater free-space optical communication systemMaria Abrahamhttps://uk.mathworks.com/matlabcentral/profile/authors/4787086tag:uk.mathworks.com,2005:Question/5659882020-07-16T11:49:22Z2020-07-16T13:52:09Zhow to read text file into table ??i want to read text file into table but i cant use readtable neither xlsread cz i have matlab 2009 so any suggestions ??narimen boucennahttps://uk.mathworks.com/matlabcentral/profile/authors/18900615tag:uk.mathworks.com,2005:Question/5653402020-07-15T10:34:57Z2020-07-16T13:49:23ZThermal Conductivity has the opposite effectI am modelling an underground thermal energy storage for my dissertation, and the aim is to see how different soils behave differently with increasing thermal energy. However, when I lower thermal conductivty for the soil, it actually becomes warmer than soil with a higher thermal conductivty - it should be the other way around. Below is my code, I'd appreicate if someone could show where I have gone wrong.
gm = multicuboid([2.1 2.2 3.7 3.95 4.2 4.45 7.45],[3.1 3.2 4.7 4.95 5.2 5.45 8.45],2);
thermalmodel = createpde('thermal');
thermalmodel.Geometry = gm
pdegplot(thermalmodel,'CellLabels','on','FaceAlpha',0.5);
figure('Position',[10,10,800,400]);
subplot(1,2,1);
pdegplot(thermalmodel,'FaceAlpha',0.25,'CellLabel','on');
title('Geometry with Cell Labels');
subplot(1,2,2);
pdegplot(thermalmodel,'FaceAlpha',0.25,'FaceLabel','on');
title('Geometry with Face Labels')
generateMesh(thermalmodel,'Hmax',1);
Water at 30 Degrees C
thermalProperties(thermalmodel,'ThermalConductivity',0.55,'Cell',1);
304 stainless steel
thermalProperties(thermalmodel,'ThermalConductivity',16.3,'Cell',2);
Crushed sandstone
thermalProperties(thermalmodel,'ThermalConductivity',2.8,'Cell',3);
Concrete
thermalProperties(thermalmodel,'ThermalConductivity',0.6,'Cell',4);
Insulation
thermalProperties(thermalmodel,'ThermalConductivity',0.13,'Cell',5);
Concrete
thermalProperties(thermalmodel,'ThermalConductivity',0.6,'Cell',6);
Soil
thermalProperties(thermalmodel,'ThermalConductivity',2,"Cell",7);
thermalBC(thermalmodel,'Face',[1 2 3 4 5 6],'Temperature',30);
thermalBC(thermalmodel,'Face',[37 38 39 40],'Temperature',12);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
[qx,qy,qz] = evaluateHeatFlux(thermalresults);
figure
pdeplot3D(thermalmodel,'FlowData',[qx qy qz]);
result = solve(thermalmodel);
pdeplot3D(thermalmodel,'FlowData',[qx qy qz],'ColorMapData',result.Temperature);Alun Owenhttps://uk.mathworks.com/matlabcentral/profile/authors/18700489tag:uk.mathworks.com,2005:Question/5660482020-07-16T13:46:25Z2020-07-16T13:46:25ZHow to use ANN for classificationHey.
I am not much familiar with ANN , MatLab . But i need to classify my satellite imagery. Can anyone please guide me how to it Amna Hafeezhttps://uk.mathworks.com/matlabcentral/profile/authors/16503559tag:uk.mathworks.com,2005:Question/4408512019-01-22T06:46:09Z2020-07-16T13:45:12ZHow to match the intensity difference of two images in matlab.I am having two input images "a" and "b". I want to match the inetsnity difference pixel by pixel of these input images. Kindly suggest how to begin with this. sakshi ahujahttps://uk.mathworks.com/matlabcentral/profile/authors/7225900tag:uk.mathworks.com,2005:Question/5660152020-07-16T12:52:40Z2020-07-16T13:44:29ZEasy way of finding zero crossing of a functionHi guys, I have tried all my attempts but not succeeding to get the correct output/plot .
I'm trying to find my zero crossings points that are implicitly the intercestion of x axis, in other words I want to find all the zero crossings points of my signal by interpolation method!.
I've searched in the other threads over this forum and find subjects that are related to what Im asking but not exactly what I want or either their answers weren't totally correct!
I have signal called y1, it's vectors of samples, I sampled it on sample frequency 2048KHz .
accordingly to @ Star Strider code:
t = [1:length(y1)]; % Time Vector
y = y1; % Signal
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Zero-Crossing Indices Of Argument Vector
zx = zci(y); % Approximate Zero-Crossing Indices
figure(1)
plot(t, y, '-r')
hold on
plot(t(zx), y(zx), 'bp')
hold off
grid
legend('Signal', 'Approximate Zero-Crossings')
when I do plot , Im not getting zero crossings points that are the intersections of x axis by interpolation method! , here's what I get:
what Im willing to do by method interpolation to find the zero crossings point which gives me like this result:
could anyone please help me how can I find the zero crossings points by interpolation to get like the above plot (zero crossings points like they are the intersections with x axis) ?
the code of my interpolation for finding the zero crossings that Im trying is: (Fs=2048Khz) - thanks to
@Walter Roberson @xszm
if size(y1,1) == 1; y1 = y1.'; end %ensure columns of signal
c = size(y1,2);
wl = (0:size(y1,1)-1) / Fs;
Iwl2=360:0.001:740; % interpolating to 0.001-nm resolution
loc_frequ1=0;
for i=1:c
y = y1(:,i);
y2=interp1(wl,y,Iwl2); % interpolating to 0.001-nm resolution
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Zero-Crossing Indices Of Argument Vector
zx = zci(y2); % Approximate Zero-Crossing Indices
loczeros1=round(Iwl2(zx));
locfrequ= ismember(Iwl2,loczeros1); % find same data from Iwl2
loc_frequ1=loc_frequ1+double(locfrequ);
end
>> c
c =
1
>> zx
zx =
0×1 empty double column vector
>> size(y1) %size of my signal data
ans =
9001 1
but the problem with this that this code didn't work and don't know what the problem is, zx isn't giving me the zero crossings point at all ..
Could anyone please help me how can I do and find the zero crossings points by interpolation in matlab? I really searched about other threads that are related to this but the answers weren't enough or didn't work for my case.Mohamed Jamalhttps://uk.mathworks.com/matlabcentral/profile/authors/17817148tag:uk.mathworks.com,2005:Question/5660452020-07-16T13:41:26Z2020-07-16T13:41:26ZHow to solve multiple DOF mass-spring linear system with attached resonators with ode45?The system is this:
I have the initial conditions, but would like to know how to solve this system with ode45 or any other solver, because they are coupled equations.
Thanks in advance!Dane Stanhttps://uk.mathworks.com/matlabcentral/profile/authors/18987614