https://www.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2019-02-18T06:10:09Ztag:www.mathworks.com,2005:Question/4434212019-02-06T03:06:05Z2019-02-18T06:10:09Zhalf bridge LLC resonant converter transfer functionHello Everyone
I am trying to design digital compensator for half bridge LLC resonant converter, I need help to calculate the easy and fast way to find the transfer function of the open loop converter. If anyone have matlab code to find the transfer function please share it with me on my email syed_shah@seu.edu.cn. Thanks in advance.
Regards,
Syed shahSikandar Shahhttps://www.mathworks.com/matlabcentral/profile/authors/13819922-sikandar-shahtag:www.mathworks.com,2005:Question/4453882019-02-17T09:26:47Z2019-02-18T06:10:05ZLittle Bit Help Required Regarding LoopHi EveryOne
I am currently working on this code
a=[1 2 3]
b=[3 4 5]
c=[34 5 6 ]
for i=1:1:3;
C = {[a];[b];[c]};
d= cellfun(@(v)v(i),C)
end
And the output is
d =
1
3
34
d =
2
4
5
d =
3
5
6
Every time loop runs it updated the last results.
I just want to save all the values means every time when loop run it keep save the last results and save the new results in the new coloumn
When I use
d(i)= cellfun(@(v)v(i),C)
The code give error
In an assignment A(I) = B, the number of elements in B and I must be the same.
Please help in this matter
Thanks
Regards
John Hockhttps://www.mathworks.com/matlabcentral/profile/authors/11079478-john-hocktag:www.mathworks.com,2005:Question/4455132019-02-18T06:07:33Z2019-02-18T06:07:33ZCould anyone help me how to find the seed of the centroid in a random manner.The following code executes and gives the result.
code:
clear all
clc
centroids=2
dimensions = 2;
iterations = 10;
dataset_subset = 2;
load test1.mat
meas = meas(:,1+dataset_subset:dimensions+dataset_subset);
dataset_size = size (meas);
[idx,KMEANS_CENTROIDS] = kmeans(meas,centroids);
With respect to the above code the centroids is fixed to 2.
Could anyone help me to modify the code in such a way that the number of centroids needs to be selected in a random manner.
jaah navihttps://www.mathworks.com/matlabcentral/profile/authors/11695462-jaah-navitag:www.mathworks.com,2005:Question/4455122019-02-18T06:07:19Z2019-02-18T06:07:19Zindexing an entire for loopHi all. Embarassed to be asking for homework help, but I can't figure out this for loop.
Essentially, I need each iteration of the inner function to save to the matrix T. The size of the matrix remains correct (61x21), but it only saves the last iteration to the matrix. I have tried the i = i+1 indexing method but my matrix blows up to 1281x21 with each column running thru both the inner and outer loops.
clear;
x = -3:0.1:3;
y = -1:0.1:1;
i = length(x);
j = length(y);
T = zeros(i,j);
for x = -3:0.1:3
for y = -1:0.1:1
T(i,j) = x^2+(2*y^2);
end
endMatthew Henryhttps://www.mathworks.com/matlabcentral/profile/authors/14523633-matthew-henrytag:www.mathworks.com,2005:Question/4454552019-02-17T19:15:07Z2019-02-18T06:07:09ZHow can I make this code more efficient?close; clear all; clc;
global cp1 vp1 cp2 vp2 value gk;
A=1; % aggregate productivity
a=0.36; % capital share of output (alpha)
b=0.96; % subjective discounting (beta)
d=0.069;% depreciation
klow=0.1;
khigh=6;
knum=250;
kgrid = linspace(klow,khigh,knum);
uf = @(x)log(x);
pf = @(x)(A*(x.^a));
cp2=[cp2,pf(kgrid(1:knum))+((1-d)*kgrid(1:knum))]; %period 2
vp2=[vp2,uf(cp2(1:knum))];
for i=1:knum %period 1
for j=1:knum
cp1(i,j)=max(pf(kgrid(i))+(1-d)*kgrid(i)-kgrid(j),0);
vp1(i,j)= log(cp1(i,j))+(b*vp2(j));
end
value=[value,max(vp1(i,:))];
[val,loc] = max(vp1(i,:));
gk=[gk,kgrid(loc)];
end
figure
subplot(211)
plot(kgrid, value)
hold on
title ( ' the value function ' )
subplot(212)
plot(kgrid, kgrid)
hold on
plot(kgrid, gk, '*')
title ( ' the decision rule ' )
saveas(gcf,'optimal2.png')
What can I do to make this code take up less lines or compute faster?Kai Jensenhttps://www.mathworks.com/matlabcentral/profile/authors/14275901-kai-jensentag:www.mathworks.com,2005:Question/4455112019-02-18T06:05:29Z2019-02-18T06:05:29ZHow to Hybrid Programming to dll file?I have such few files to use Hybrid Programming to generate a dll file. Idon't know how to do it step by step.
Thanks in advance.
Crystal Lihttps://www.mathworks.com/matlabcentral/profile/authors/6653081-crystal-litag:www.mathworks.com,2005:Question/4454592019-02-17T20:31:27Z2019-02-18T06:04:29ZFor Loops with Struct and FieldsMy data is in a structure/filed format B{x}.F{x}.signals.values, The structures and fields are consistant ,Struct B{x} where x =1:inf, F{x} and signals are the same for every iteration of B{x}. However the values are of diffrent sizes and i need to vertically cancatenate to be able to plot the values in on graph.
I have been using the loop function below to try to get te data into one cell C so I use the Padcat function but either 6 or 8 produced errors
C ={};
cj =1;
j =1;
for j = 3:numel(B)
S = B{1,j};
fn = fieldnames(B{1,j}).';
for y = fn{1,j}
C{cj} = S.(y{:}).signals.values;
cj = cj+1;
end
end
Is there a way to better concantenate large cell or why do i get "Brace indexing is not supported for
variables of this type"
Thanks.
Franchttps://www.mathworks.com/matlabcentral/profile/authors/4013188-franctag:www.mathworks.com,2005:Question/4455062019-02-18T04:51:52Z2019-02-18T06:01:52ZHow Can I count the ascending runs in array ?if I have an array such as
x=[1 2 3 2 1 2 4 5]
I would generate a binary array for binary search
binaryarray= [1 1 1 0 0 1 1 1]
in binaryarry i would sign 1 along with ascending runs while 0 along with descending runs.Faraj Alyamihttps://www.mathworks.com/matlabcentral/profile/authors/9511051-faraj-alyamitag:www.mathworks.com,2005:Question/4454682019-02-17T21:29:49Z2019-02-18T05:45:35ZWhy am I not getting an array of answers from this operation?t=linspace(0,3.5,1000);
u=4*exp^(-0.45*t.)*sin(4*t. + 0.5);
I want u to be an array that is the same size as t, but whenever i try to run this matlab says I have a parse error at ')' referring to the first closing parenthesis. I also tried making u an anonymous function of t but I could not get that to work either. Zachary Heupelhttps://www.mathworks.com/matlabcentral/profile/authors/14658811-zachary-heupeltag:www.mathworks.com,2005:Question/791132013-06-14T18:16:47Z2019-02-18T05:42:33ZHow to generate a geographical heat map? (worldwide, country-level granularity)I want to create a geographical heat map like the following in MATLAB:
<<http://i.stack.imgur.com/64DJY.png>>
Each color is based on a list of country with a percentage associated to each of them:
Country with Codes: % of Hits
- United States (US): 36.29%
- India (IN): 18.24%
- United Kingdom (GB): 12.93%
- Spain(ES): 8.22%
- Australia (AU): 3.32%
- Canada (CA): 3.05%
- Germany (DE): 2.49%
- Netherlands (NL): 1.66%
- Israel (IL): 1.39%
- China (CN): 0.83%
How can I do it in MATLAB?
I looked at http://mathworks.com/products/mapping and Googled around but I didn't find any easy way to do it. Such kind of maps are commonly used (e.g. straightforward to do with the <https://developers.google.com/chart/interactive/docs/gallery/geomap?hl=en Google Chart API>) so I'm hoping someone here shares his/her experience.
Thanks,
Franck
[1]: http://i.stack.imgur.com/64DJY.pngFranck Dernoncourthttps://www.mathworks.com/matlabcentral/profile/authors/2210440-franck-dernoncourttag:www.mathworks.com,2005:Question/4455012019-02-18T04:23:19Z2019-02-18T05:41:57ZI am having set of images in four different classes. for all those i need to save thier histograms by creating the folders seperatly. How can save these?foldername = 'descriptor';
des = 'hist';
dataset = 'OASIS_MRI';
type = 'gallery';
class_names = ['{c1}','{c2}','{c3}','{c4}'];
image_names1 = ['img1.jpg','img2.jpg'.......];
image_names2 = ['img1.jpg','img2.jpg'........];
image_names3 = ['img1.jpg','img2.jpg'.......];
image_names4 = ['img1.jpg','img2.jpg'.......];
load gallery.mat
for class = 1:length(gallery)
for image = 1:gallery(class).Count
im = imread(gallery(class).ImageLocation{image});
des=histogram(im);
end
end
if~exist([foldername '\',dataset '\',type], 'dir')
mkdir= ([foldername '\',dataset '\',type]);
end
filename = ([foldername '\',dataset '\',type '\',num2str(class_names(class)) '\', image_names(1:end-3),'.mat']);
save(filename,des);Sneha Chennamsettyhttps://www.mathworks.com/matlabcentral/profile/authors/14582937-sneha-chennamsettytag:www.mathworks.com,2005:Question/4455102019-02-18T05:41:11Z2019-02-18T05:41:11ZHow to store each logical linear array in a matrix?clc;
close all;
clear;
workspace;
folder = 'D:\data_set';
filepattern = fullfile(folder, '*.png');
srcFiles = dir(filepattern);
numImages = length(srcFiles);
t=0:0.001:2*pi;
for k = 1 : numImages
fullFileName = fullfile(folder, srcFiles(k).name);
a = imread(fullFileName);
bwimg =bwareafilt(~a, 1);
s=regionprops(bwimg,'Orientation');
theta = s.Orientation;
if theta>=0 && theta<90
phi=90-theta;
Y=imrotate(bwimg,phi);
else
phi=90-(-theta);
Y=imrotate(bwimg,-phi);
end
s1=regionprops(Y,'Centroid','BoundingBox','MajorAxisLength','MinorAxisLength','Area');
Area = [s1.Area];
index = find(Area==max(Area));
circleCenterX = s1(index).Centroid(1);
circleCenterY= s1(index).Centroid(2);
diameters = mean([s1(index).MajorAxisLength s1(index).MinorAxisLength],2);
r1 =1*diameters/16;
r2=2*diameters/16;
r3=3*diameters/16;
r4=4*diameters/16;
r5=5*diameters/16;
r6=6*diameters/16;
r7=7*diameters/16;
r8=8*diameters/16;
r9 =9*diameters/16;
r10=10*diameters/16;
r11=11*diameters/16;
r12=12*diameters/16;
r13=13*diameters/16;
r14=14*diameters/16;
r15=15*diameters/16;
r16=16*diameters/16;
radii=[r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16];
[g,h]=size(radii);
[r,c]=size(Y);
bw=false(r,c);
for j=1:h
thisRadius = radii(1, j);
x = circleCenterX + thisRadius * sin(t);
y = circleCenterY + thisRadius * cos(t);
bw = bw|poly2mask(x,y,r,c);
boundaries = bwboundaries(bw);
thisBoundary = boundaries{1};
x1=thisBoundary(:,2);
y1=thisBoundary(:,1);
indexes = y1<circleCenterY; % Only those in the upper half.
xTop = x1(indexes);
yTop = y1(indexes);
for l=1:length(xTop )
profile(l) = Y(yTop(l),xTop(l));
A{k,j}=profile;
end
end
end
For each image in the dataset I am repeating the same procedure. But unable to store different length profile. For First image its ok. But for other images A{k,j}=profile storing the same length profiles although their radius is different . How to resolve this ? Zara Khanhttps://www.mathworks.com/matlabcentral/profile/authors/10893209-zara-khantag:www.mathworks.com,2005:Question/4454832019-02-18T00:37:21Z2019-02-18T05:34:58ZVectorized Search of substrings in Cell Array I have a cell array of strings and I want to match substrings to produce a boolean vector to then extract the elements of interest.
I want strfind to behave like strcmp.
t = {'abcde','bcde','abc','ac'};
i = strcmp(t,'bcde')
0 1 0 0
for example - for 'bc', I want:
1 1 1 0
but using strfind, I get :
i = strfind(t,'bc')
[2] [1] [2] []
then:
~isempty(i)
1
or:
i==[]
but this returns: 'Undefined function 'eq' for input arguments of type 'cell'.'
I think cellfun() with strfind() and isempty() might work but I'm confused how to use it.
v= cellfun(@(x) strfind(t,'bc'), t, 'UniformOutput', false)
v =
{1x4 cell} {1x4 cell} {1x4 cell} {1x4 cell}
v{1}
ans =
[2] [1] [2] []
I want boolean array: [1 1 1 0]Timothyhttps://www.mathworks.com/matlabcentral/profile/authors/169024-timothytag:www.mathworks.com,2005:Question/4390472019-01-09T21:38:50Z2019-02-18T05:20:32ZHow to auto-generate the test cases using Simulink Design Verifier on a huge model which has unit models inside it. How can i avoid the error active configuration cannot be changed in compilation or simulation? As per the process I have been using this Simulink design Verifier for auto generating the test cases. When I am trying to do on the HVAC module which has 20 to 25 unit models assigned to it. I am supposed to generate the test cases for the huge model which has 324 inputs and 171 outputs. Inside the HVAC module, there are many unit models which are like a reference to this huge model.
I would like to avaoid an error which is relating to the active configuration changes are not done while compilation or simulation. The stop mentioned is "inf". I have checked the configuration pane and changed the process accordingly. There is one more issue is that, when I am trying to correct the error and trie to rebuild the process, it wont start again. The error dialog box says that there is one unit model which is compiling or simulating mode.
I would like to know is their anything that I can avoid the errors to do my work.Kameswari Vemurihttps://www.mathworks.com/matlabcentral/profile/authors/13974928-kameswari-vemuritag:www.mathworks.com,2005:Question/4455092019-02-18T05:18:50Z2019-02-18T05:18:50ZI am using psychtoolbox with brain vision recorder, I want to use trigger using parallel port. How to do it? Is anybody have code for doing this? i have brainvison recorder and we are using actichamp EEG machine. Dhiraj Jagadalehttps://www.mathworks.com/matlabcentral/profile/authors/8316696-dhiraj-jagadaletag:www.mathworks.com,2005:Question/4455082019-02-18T05:12:30Z2019-02-18T05:12:30ZAxes not appearing when I save plot in a folderWhen I am plotting a figure, axes are showing in the plot editor
But when I am directly saving the plot as .png in a folder, axes are not showing up.
I want all four axes, so my figure looks complete.
hh=pcolor(lon,lat,ghs)
set(hh,'EdgeColor', 'none');
box on
Color=[1,1,1;
1,0.8,0;
1,0,0;
0.4,0,0];
colormap(Color);
set(gca,'FontSize',20)
caxis([0 3])
cd ('C:\Users\soura\Documents\synop\figures\ch2_2\');%When I am saving it here, the axes are not apearing. but it is applearing in the plot editor
saveas (gcf,'a.tiff');Sourangsu Chowdhuryhttps://www.mathworks.com/matlabcentral/profile/authors/11354467-sourangsu-chowdhurytag:www.mathworks.com,2005:Question/4454922019-02-18T03:05:14Z2019-02-18T05:11:45ZHow obtain the Y value that corresponds to the largest X value for a number of plots?Hi,
I am trying to write a code that gives me the Y value that corresponds to the largest X value for a number of plots.
I have a code that interpolates X values from Y. I just need the oposite and for the largest X values instead.
clear; clc;
Folder = cd;
N=170;
x2 = zeros(N, 10);
for k = 1:N;
Driftt = sprintf('Disp%d.out', k);
Reactt = sprintf('React%d.out', k);
matDrift = importdata(fullfile(Folder, Driftt));
matReact = importdata(fullfile(Folder, Reactt));
x1= matDrift(:,1);
y1= matDrift(:,2);
[x3, ix] = unique(x1);
y3 = y1(ix);
A=dlmread('Time.txt');
for i=1:size(A,2)
x2 (k,:) = interp1(y3, x3, A(:,i), 'linear');
temp=x2(k,:);
temp(isnan(temp))=0.05;
x2(k,:)=temp;
fid=fopen(['result_' num2str(i) '.txt'],'a');
fprintf(fid,'%f\n',x2(k,:));
fclose(fid);
end Ismail Qeshtahttps://www.mathworks.com/matlabcentral/profile/authors/10292327-ismail-qeshtatag:www.mathworks.com,2005:Question/1060032013-11-11T05:00:00Z2019-02-18T05:10:20ZHow do I install a MATLAB client for a network license?I am trying to find instructions on how to install a MATLAB client for a Network-based (concurrent or network named user) license.
MathWorks Support Teamhttps://www.mathworks.com/matlabcentral/profile/authors/4622813-mathworks-support-teamtag:www.mathworks.com,2005:Question/3907162018-03-26T10:49:56Z2019-02-18T05:08:13ZError using load Unable to read file 'matlab.mat': no such file or directory.I receive this message "Error using load Unable to read file 'matlab.mat': no such file or directory." when I tried to run the simulation of Feedback linearization of an SRM 8/6. what does it mean, help me with that plz.hicham chouchouhttps://www.mathworks.com/matlabcentral/profile/authors/5372214-hicham-chouchoutag:www.mathworks.com,2005:Question/4454962019-02-18T03:53:18Z2019-02-18T05:05:52ZLooking 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://www.mathworks.com/matlabcentral/profile/authors/14560433-ning-jitag:www.mathworks.com,2005:Question/4455072019-02-18T05:04:47Z2019-02-18T05:04:47Zproblem occur when i convert the .csv file into .mat fileHello everyone,
i create a dataset in matlab is 1500X5 . i convert it into .csv for labeling the data. after the labeling i convert back into the .mat format but when i access the labeled dataset in matlab the columns are shown me like 1500X1...1500X1. how to resolve this problem .
in the below i attach screemshot of my dataset before and after conversion.
first image shown before the labeling data .mat file look like this.
after labeling when i convert .csv to .mat the file is look like the ablove image.Riya Botharahttps://www.mathworks.com/matlabcentral/profile/authors/12894484-riya-botharatag:www.mathworks.com,2005:Question/4455052019-02-18T04:49:49Z2019-02-18T05:04:34ZGfortran not found by mex -setupI'm trying to set up mex compilers on R2016b. I have GCC 8.2.0 installed (same version for gcc-c++ and gfortran). I was able to set up the GCC C and C++ compilers without a problem. When I try mex -setup FORTRAN I get an error:
Error using mex
No supported compiler or SDK was found. For options, visit
http://www.mathworks.com/support/compilers/R2016b/glnxa64.html.
But gfortran is definitely there:
system('which gfortran')
/usr/bin/gfortran
ans =
0
I understand that this is several versions newer than the officially supported version, but in my experience MATLAB usually just gives you a warning about using an unsupported version of the compiler rather than flat-out refusing to use it. What could be causing MATLAB to fail in setting up the Fortran compiler?jg614https://www.mathworks.com/matlabcentral/profile/authors/7433294-jg614tag:www.mathworks.com,2005:Question/4454932019-02-18T03:31:03Z2019-02-18T04:54:39Z3D point CloudI am trying to get a 3D point cloud from live video using 2 usb webcms but as I run the code two axis shows up and the following error shows up:
ERROR:
Error using imaq.internal.VideoDeviceInternal (line 344)
winvideo: The device associated with device ID 2 is already in use. A new videoinput object cannot be
created for this device while it is in use.
Error in imaq.VideoDevice (line 270)
Code:
output_dir = 'C:\Users\HITESH\Desktop\Matlab';
%%set up webcam
leftCam = imaq.VideoDevice('winvideo', 2, 'YUY2_640x480');
rightCam = imaq.VideoDevice('winvideo', 1, 'YUY2_640x480');
%%load stereo parameters if required
if ~exist('stereoParams', 'var')
load stereocalibration.m;
end
ax = axes;
maxDepth = 5;
while true
imageLeft = step(rightCam);
imageRight = step(leftCam);
[J1, J2] = rectifyStereoImages(imageLeft, imageRight, stereoParams);
disp = disparity(rgb2gray(J1), rgb2gray(J2), 'DisparityRange', [0, 112]);
pointCloud = reconstructScene(disp, stereoParams) ./1000;
z = pointCloud(:,:,3);
z(z<0) = NaN;
z(z>maxDepth) = NaN;
pointCloud(:,:,3) = z;
if ~ishandle(ax)
break;
else
showPointCloud(pointCloud, J1, 'VerticalAxis', 'Y', 'VerticalAxisDir', 'Down', 'Parent', ax);
xlabel('X (m)');
ylabel('Y (m)');
zlable('Z (m)');
xlim(ax, [-.8, .8]);
ylim(ax, [-.8, .8]);
zlim([ax, maxDepth]);
drawnow;
end
end
release(leftCam);
release(rightCam);
MATLAB: R2015aHitesh Phttps://www.mathworks.com/matlabcentral/profile/authors/14613530-hitesh-ptag:www.mathworks.com,2005:Question/4455042019-02-18T04:47:04Z2019-02-18T04:47:04ZPlotting multiple times in a functionHi , I amd new using matlab and I would want to know how can I plot every generation of child ( xh) and see how has improve each generation in each iteration of jj. Total of generations are 200.
Code is below.
clear all
close all
clc
f = @(x,y) x*exp(-x^2 -y^2);
Ge = 200; %generations
N = 50;
D = 2;
xl = [-2 ; -2];
xu = [2 ; 2];
aptitud = zeros(1,N);
x = zeros(2,N); %parents
for i=1:N
x(:,i) = xl+(xu - xl).*rand(2,1);
end
for jj=1:Ge
for i=1:N
fx = f(x(1,i),x(2,i));
if fx >= 0
aptitud(i) = 1/(1+fx);
else
aptitud(i) = 1+abs(fx);
end
end
xh = zeros(2,N); % children
for k=1:2:N
p1 = seleccion(aptitud);
p2 = p1;
while p2 == p1
p2 = seleccion(aptitud);
end
[h1,h2] = cruza(x(:,p1),x(:,p2));
xh(:,k) = h1;
xh(:,k+1) = h2;
end
% disp(xh);
pm = 0.3;
for i=1:N
for j=1:D
if rand > pm
else
xh(j,i) = xl(j) + (xu(j) - xl(j))*rand();
end
end
end
x = xh;
end
Cesar Ramirezhttps://www.mathworks.com/matlabcentral/profile/authors/14648729-cesar-ramireztag:www.mathworks.com,2005:Question/4455002019-02-18T04:09:39Z2019-02-18T04:39:52ZWhat is wrong with this code?
I am new to Matlab, which is probably very apparent from the above picture. I am trying to display that the left side of the equation on line 4 is equal to the function on the right after the n and x have been defined by the user. Any help would be much appreciated. Thanks!matlabnoobhttps://www.mathworks.com/matlabcentral/profile/authors/14720103-matlabnoobtag:www.mathworks.com,2005:Question/4454822019-02-18T00:27:05Z2019-02-18T04:37:13ZSaving multiple figures of loop in one subplotIs it possible to save figures of different loops in 1 sub plot?For example:there are 3 different training and testing datasets.I want to save the results of all three datasets in 1 subplot.Thank you.
Suppose dataset of 3 homes
data1 =Home 1;
date2=Home 2;
date3=Home 3;
i=data1+data2+data3;
for j=1:i
-----
end
% After training a model;
results_home1=actual Vs Predicted ; % suplot 1
results_home2=actual Vs Predicted ; % suplot 2
results_home3=actual Vs Predicted ; % suplot 3
% All the above suplots in 1 figureAlihttps://www.mathworks.com/matlabcentral/profile/authors/14555415-alitag:www.mathworks.com,2005:Question/4455022019-02-18T04:34:03Z2019-02-18T04:34:03ZHow can I get exact analytical symbolic solution of a Cosine series from 1 up to nth harmonic?Hi, I am trying to solve for
syms n m d
m=2*n-1;
eqn1=symsum(1/m^2,n,1,Inf)
eqn = symsum(cos(m*d)/m^2,n,1,Inf)
I get the correct answer for sum of (1/m^2) equal to
eqn1 = pi^2/8
running that code. But when I try to get sum of cos(m*d)/m^2, it comes with the following expression even I assume and simplifiy it.
piecewise(in(d, 'real'), - exp(-d*1i)/2 - exp(d*1i)/2 + (exp(-d*1i)*hypergeom([-1/2, -1/2, 1], [1/2, 1/2], exp(d*2i)))/2 + (exp(d*1i)*hypergeom([-1/2, -1/2, 1], [1/2, 1/2], exp(-d*2i)))/2)
assume(d,'integer')
assume(d,'real')
assume(d<pi & d>-pi)
simplify(piecewise(in(d, 'real'), - exp(-d*1i)/2 - exp(d*1i)/2 + (exp(-d*1i)*hypergeom([-1/2, -1/2, 1], [1/2, 1/2], exp(d*2i)))/2 + (exp(d*1i)*hypergeom([-1/2, -1/2, 1], [1/2, 1/2], exp(-d*2i)))/2))
The simplified expression would be
pi^2/8(1-2*abs(d)/pi)
Can anyone suggest me whether is there any way to simplify the long piecewise equation into the above simple equation?
Any help is highly appreatiated. Mukulhttps://www.mathworks.com/matlabcentral/profile/authors/11283790-mukultag:www.mathworks.com,2005:Question/4454902019-02-18T02:33:18Z2019-02-18T04:21:57ZHow to remove this error, I get it in all my programme?Error using gradient (line 49)
Too many output arguments.
Error in feature (line 21)
[gx gy]=gradient(G);
Error in images.internal.isFigureAvailable (line 9)
if feature('showFigureWindows')
Error in imshow (line 207)
if ~images.internal.isFigureAvailable()
Error in Untitle (line 2)
imshow(A);
please, Help me as soon as possible.riddhi thakkarhttps://www.mathworks.com/matlabcentral/profile/authors/13146611-riddhi-thakkartag:www.mathworks.com,2005:Question/4454422019-02-17T18:18:38Z2019-02-18T04:11:31Z "mat" file not getting logged-parrot mini droneHello,
I configured the parrot mini drone with MATLAB R2018b. The drone operates correctly but when I try to get the MAT file after stopping the program, it displays the following error, "MAT-File not found on mini drone. Ensure that MAT-File logging is enabled and build the model again. Note that MAT-File logging is only available if you have Simulink Coder."
I have already checked that I have a liscenced version of Simulink Coder and also, before uploading my flight control system on the drone, I run "set_param('FlightControlSystem','MatFileLogging','on')" command. However, still, the MAT file is not logged. The "Flight log" file is getting created.
Please could you help on this issue.Jasvir Virdihttps://www.mathworks.com/matlabcentral/profile/authors/14397810-jasvir-virditag:www.mathworks.com,2005:Question/4454992019-02-18T04:05:55Z2019-02-18T04:05:55ZDeploy Algorithm on the Raspberry Pi Hardware using R2017b version and get the error for creating configuration object for hardware
board=targetHardware(r,'myApplication')
received error
undefined function or variable targetHardwaAshwini Patilhttps://www.mathworks.com/matlabcentral/profile/authors/8461857-ashwini-patiltag:www.mathworks.com,2005:Question/4454692019-02-17T21:32:25Z2019-02-18T04:01:21ZDistance between all elements of row vectorSo, I have 1x200 matrix, (row vector). I want to find difference (x(0)-x(1), x(0)-x(2)...) between all elements of an array. How do I do that ?
I should be having 200x200/2 values.Anahttps://www.mathworks.com/matlabcentral/profile/authors/8183027-anatag:www.mathworks.com,2005:Question/4454982019-02-18T03:57:25Z2019-02-18T03:57:25ZHow can I get Levy SV market model matlab code?Hi,
I would like to request you to get the code of Brandroff Nielsen Shepherd OU gamma clibration market model. I want to fit it with S&P500 market data.
Do you have any matlab code of it?G M Fahad Bin Mostafahttps://www.mathworks.com/matlabcentral/profile/authors/14800345-g-m-fahad-bin-mostafatag:www.mathworks.com,2005:Question/4454352019-02-17T17:30:34Z2019-02-18T03:56:22ZHow 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://www.mathworks.com/matlabcentral/profile/authors/14804435-teddy2018tag:www.mathworks.com,2005:Question/4454972019-02-18T03:54:23Z2019-02-18T03:54:23ZWhy am I getting "Error using singularity"while evaluating the MeijerG function in matlab I m trying to evaluate the Meijer G function in a part of a program.Here an,ap,bm,bq are the vectors initialised,C and v are the variables initialised
syms nu
z=meijerG( an, ap, bm, bq,(C*((v/nu)^v)));
for i=1:80
ok(i,:)=( subs(z,nu,i) );
end
I am getting the error
Error using sym/meijerG (line 48)
Singularity.
Error in ffffff (line 34)
z=meijerG( an, ap, bm, bq,(C*((v/nu)^v)))Jyotsna Sri Sai Tallurihttps://www.mathworks.com/matlabcentral/profile/authors/14641464-jyotsna-sri-sai-talluritag:www.mathworks.com,2005:Question/4454952019-02-18T03:50:22Z2019-02-18T03:50:22ZFind unknown transfer function between two images using a neural networkI would like to know if it is possible/how I would be able to have an algorithm predict what the transfer function between two images is. Say I have many images as my sample data, and I apply a uniform effect on every one of those images, maybe a hue change or change in brightness. Is there a process that would then be able to analyze the input original data, and compare to the effected images, and provide a transfer function that is approximately the effect that was applied? If possible how would I do this?Lucas Martinezhttps://www.mathworks.com/matlabcentral/profile/authors/9611948-lucas-martineztag:www.mathworks.com,2005:Question/4454842019-02-18T00:49:22Z2019-02-18T03:39:02ZInsert two elements in a multidimensional arrayHi, I want to insert two elements (h1,h2) into my multi array called xh after its initialized all with zeros.
N = 50;
xh = zeros(2,N);
[h1,h2] = cruza(x(:,p1),x(:,p2));
%Insert h1 and h2 into xh
The function "cruza" returns elements to insert into xh
function [xh1,xh2] = cruza(xp1,xp2)
D=2;
pc = randi([1 D]);
xh1 = [xp1(1:pc) ; xp2(pc+1:D)];
xh2 = [xp2(1:pc); xp1(pc+1:D)];
Cesar Ramirezhttps://www.mathworks.com/matlabcentral/profile/authors/14648729-cesar-ramireztag:www.mathworks.com,2005:Question/4453892019-02-17T10:16:00Z2019-02-18T03:38:05ZIssue with DisplayName plot function in a loopHello all,
I am having an issue when trying to plot the display for specific vectors in a loop. Here is my code:
clf;
cc = jet(32);
for i=1:31
check_NaN=~isnan(CN0_Plot_GPA_L1CA4(i,:));
val_index=find(check_NaN);
if ~isempty(val_index)
p(i)=plot(Time(1:N_Packet)-fix(Time(1)),CN0_Plot_GPA_L1CA4(i,:),'color',cc(i,:), 'marker','+','DisplayName',['SV=' num2str(i)]);
hold on
end
end
legend(gca,'show')
grid on;
datetick('x','HH:MM');
xlabel(datestr(fix(Time(1))));
ylabel('CN0(dBHz)');
title('GPS CN0 for L1CA modulation ');
With this code I am getting a plot with all indexes i plotted.
Now, when I am doing a very similar algorithm but this time removing the abscissa in the plot (no more Time(1:N_Packet) in the plot) it is working as expected:
clf;
cc = jet(32);
for i=1:31
check_NaN=~isnan(CN0_Plot_GPS_L1CA4(i,:));
val_index=find(check_NaN);
if ~isempty(val_index)
%
p(i)=plot(CN0_Plot_GPS_L1CA4(i,:),'color',cc(i,:), 'marker','+','DisplayName',['SV=' num2str(i)]);
%
hold on
%
end
end
legend(gca,'show')
grid on;
ylabel('CN0(dBHz)');
title('GPS CN0 for L1CA4 modulation ');
Any idea on how to solve this will be much welcome!
Best regardsFranck Bordehttps://www.mathworks.com/matlabcentral/profile/authors/1804233-franck-bordetag:www.mathworks.com,2005:Question/3731212017-12-15T11:45:00Z2019-02-18T03:25:25Z"Get More Apps" doesn't workI click "Get More Apps" in the "Apps" section of MATLAB 2017b but the link does not work. I have to physically reinstall the entirety of MATLAB and select the apps I want to download then. "Install App" and "Package App" can be opened but I have to pay to download these files from the MATLAB website, even though it's free when I install the program fully as I have an academic license until 2020. I also cannot install all of the apps as it takes hours to download and uses up lots of memory.
The "Log In" button in the top right also does not work.BKC1995https://www.mathworks.com/matlabcentral/profile/authors/8832140-bkc1995tag:www.mathworks.com,2005:Question/4406792019-01-21T07:41:48Z2019-02-18T03:12:48ZHow to find white line in image using matlab?I want to detect the horizontal white line in the image (inside the circle) so which commands and program to use?
Lakshay Gopalkahttps://www.mathworks.com/matlabcentral/profile/authors/14594485-lakshay-gopalkatag:www.mathworks.com,2005:Question/4453532019-02-16T23:49:33Z2019-02-18T03:10:08ZFunction With While Loop HelpHello--
So I need to calculate time, flow rate, height, and velocity of water exiting a cylindrical container until the container is empty. I must use a while loop within a function to do so. I am supposed to break the loop once h (height) is slightly larger than 0 so h>0. I need to define a counting variable and start at t = 0.
This is my code for the function so far:
function [Q,h,t,V] = hw4_func_BDP(Initial_Height,Outer_D,Inner_D)
p = 1000; %(kg/m^3) pressure of water
g = 9.81; %(m/s^2) acceleration due to gravity
k = ((d^2)/(D^2))*sqrt(2*g); %constant with diameters of large hole vs exit hole
%Outputs (all vectors)
t = 0 %Time
h = sqrt(h0-.5*k.*t).^2 %Fluid Height
V = sqrt(2*g.*h) %Velocity
Q = pi*(Inner_D/2)^2 .*V %Flow Rate
j = 1
while h > 0
%I am uncertain what to do here
j = j+1
end
The inputs in my script are:
h0 = 2; %initial height
D = 1; %outer diameter
d = .1; %inner diameter
Also, I am supposed to calculate these as vectors, should I define them in my script as blank vectors before hand? Like t = [] h = [] V = [] Q = []
Please help!!
Brian Peopleshttps://www.mathworks.com/matlabcentral/profile/authors/14623665-brian-peoplestag:www.mathworks.com,2005:Question/4453592019-02-17T02:16:38Z2019-02-18T03:04:13ZIf else statement for pixel intensityHow would you go about writing a function to create a contrasted image of matrix A. Then display the contrasted image using a tolerance of 100 and then 150 in two separate figures. I'm pretty sure that I have to do a if else statement but I'm not sure about everything else.Merranda Schmidhttps://www.mathworks.com/matlabcentral/profile/authors/14619508-merranda-schmidtag:www.mathworks.com,2005:Question/181222011-10-12T15:24:15Z2019-02-18T03:02:24ZWingdings (and other symbol fonts) appear as default fontI am using Matlab R2011b on OS X 10.6.8.
The listfonts command shows that Wingdings is available, but when I try to use it in a figure, it appears as the default font. This seems to be true of other symbol fonts like Symbol and Zapf Dingbats.
The fonts work fine on another machine running the latest version of OS X but I can't figure out what is different between them. Both machines are running the same version of Java.
Any ideas?Alanhttps://www.mathworks.com/matlabcentral/profile/authors/3113298-alantag:www.mathworks.com,2005:Question/4401292019-01-16T23:16:01Z2019-02-18T02:53:17ZApp Designer extremely slow to save and runI am developing a MATLAB App using App Designer and the program has become extremely slow. Problems that I have include the following:
Delays upto several minutes long between clicking "save" and the program actually saving, as denoted by removal of the asterisk after the file name.
Delays of many minutes after hitting "run"
Delay of many seconds when trying to paste copied text.
Inconsitency or inability of pasting copied text to the point where text is pasted in unintended part of code
Delays in removal of error messages when adding conditional statements
Spiking of CPU and memory usage when "save" or "run" are clicked.
My App is currently 8500 lines of code and contains roughly 120 callbacks and 200 components, along with 20 internal functions. It also calls roughly 20 different external functions.
I have used the same code in 64 bit macOS (High Sierra on 2018 MacBook Pro, 2.6 GHz Intel Core i7, 16 GB 2400 MHz DDR4 memory) and Windows 10 (Dell Inspirion, 3.6 GHz Intel Core i7, 16 GB RAM) and experience similar problems with delays. My temporary solution has been to use the App Designer for ~30 minute periods, close all MATLAB instances, then reopen, and do this repeatedly. App Designer seems to perform better when first started and gradually get slower. I also use MATLAB Compiler to create stand-alone execuatables of the App that I am creating. The compiled versions run fairly smoothly, but editing and debugging them in App Designer has become a major bottleneck of productivity. I have already unchecked "Enable app coding alerts" with the hope of reducing the lag, but this does not seem to have a major effect. I am at the point where I may need to abandon use of App Designer if there are no solutions to this problem.
I notice that most example Apps on Mathworks website are relatively simple so I wonder whether this is a common probelm simply due to the size of the App?
Has MATLAB tested scalability of the App Designer?
Are there any recommendations to improve speed when editing in App Designer?
Has anyone successfully built an App of this scale without dramatic slowdown occuring in the App Editor?
If so, are there any suggestions available or example files of this scale available?
Unfortunately, I am not able to post the code as it is proprietary.
Thank you for you help.Joseph Smalleyhttps://www.mathworks.com/matlabcentral/profile/authors/13751435-joseph-smalleytag:www.mathworks.com,2005:Question/4453702019-02-17T04:56:28Z2019-02-18T02:32:21ZNewtons Method, help calling anon function inside of function file Ok so I have been tasked with writing a file myNewton which finds the root of any function given the listed inputs. I am maybe misunderstanding how to implement the method in general, but my matlab related question pertains more to the nature of calling anony functions inside of function files. I do not do this here but I anticipate that the best way to solve this problem is to do that. I am basically confused! Any help is appreciated, here is what I have so far.
function p = myNewton(f,fprime,x0,tol)
%input f, anonymous function for root finding problem
%input fprime, anonlymous function, the derivative of f
%input x0, an initial guess
%input tol, a tolerance (method will stop when successive iterates are within tol of each other)
%output p, a root f(p) = 0
x(1) = x0 - (f(x0)/fprime(x0));
k = 2;
ex(1) = abs(x(1)-x0);%error
while (ex(k-1) >= tol) %while my error is greater than tolerance
x(k) = x(k-1) - (f(x(k-1))/fprime(x(k-1)));
k = k+1;
end
end
code to call function;
%As a test, the root of f(x) = x+2^x is -0.64118574
% define f, fprime, an initial guess (you can use 1), and use a tolderance of 1e-6
% send these into the function and store the result as the variable p
format long % to display more digits
x0=1;
tol=1e-6;
myNewton('x+2^x','diff(x+2^x)',x0,tol)
Peter M Hoganhttps://www.mathworks.com/matlabcentral/profile/authors/14581397-peter-m-hogantag:www.mathworks.com,2005:Question/4454752019-02-17T22:49:45Z2019-02-18T02:19:50ZNot enough input arguments - ODE45Hi,
I am struggling to solve the attached non-linear differential equation. The Hertz contact law is what I'm trying to solve - steel ball impacting into a flat plate. Not enough input arguments comes up for line 23.
My current code is as follows:
%Trial
%y"+(1/8)*((I*D)^(1/2))*(3/2)*(K)*(y^1/2)*y')+(K/M)y;
function dydt=f(t,y)
%Constants
Es=210000000; %Youngs Modulus of Glass/Steel Plate (Pa)
rs=10; %radius of impactor (mm)
M=0.0329; %impactor mass (kg)
a=0.2; %length of plate (m)
b=0.2; %width of plate (m)
h=0.008; %plate thickness (m)
vs=0.3; %Poissons ratio of steel/glass
ps=7800; %density of steel/glass plate (kg/m3)
volume=a*b*h; %volume of plate (m3)
I= ps*volume; %total mass of steel/glass plate (kg)
z1=(1-vs^2)/Es*pi;
z2=(1-vs^2)/Es*pi;
K=(4/3*pi)*(rs^(1/2))*(1/(z1+z2)); %contact stiffness
D=(Es*h^3)/(12*(1-vs^2));
%Define inputs
dydt=zeros(2,1);
dydt(1)=y(2);
dydt(2)=(-1/8)*((I*D)^(1/2))*(3/2)*(K)*(y(1)^1/2)*y(2)-(K/M)*y(1);
timerange = [0 100];
initialvalues = [0 0];
[t,y] = ode45(@f,timerange,initialvalues);
plot(t,y(:,1))
ylabel('y')
xlabel('x')
I am unsure where i've gone wrong, be that in the code or in the approach.
Any help would be greatly appreciated!Tom Atwellhttps://www.mathworks.com/matlabcentral/profile/authors/11158714-tom-atwelltag:www.mathworks.com,2005:Question/4454742019-02-17T22:49:39Z2019-02-18T02:18:30Zperform calculation using for loopSo I have to use a for loop because I'm a student and the teacher said so. I've been trying to figure this one out and I'm sure theres a simple solution but because we are using matlab there aren't a whole lot of tutorials on using for loops when array operations are so much better.
I need to calculate the specific humidity using a for loop.
The equation is: q = (E*e)/P
where E = 0.622, e is a 96x144 matrix and, P represents p1 in my code which is another 96x144 matrix
I've coded something but I feel like the for loop is too simple.
Also the for loop and array operation return different values...is this normal?
% use for loop to calculate specific humidity
for q = 1:numel(p1)
q_for = (0.622.*e)./(p1(q));
end
% calculate specific humidity using array operations
q_array = (0.622.*e)./p1;Adam Kevin Francis Bakerhttps://www.mathworks.com/matlabcentral/profile/authors/14522742-adam-kevin-francis-bakertag:www.mathworks.com,2005:Question/4454702019-02-17T22:03:01Z2019-02-18T02:15:28ZSwitch to write programsUse switch to write a program to prompt the user to enter an integer between 1 to 10 then display the English word corresponding to it. You can assume that the user inputs integers between 1 to 10.
How can I modify my program hence it works for bigger numbers? (e.g. 1-100)
I now do my 1-10 in this way. Thanks a lot!!
>> number = input('Input an integer: ');
Input an integer: 3
>> switch number
case 1
disp('one');
case 2
disp('two');
case 3
disp('three');
case 4
disp('four');
case 5
disp('five');
case 6
disp('six');
case 7
disp('seven');
case 8
disp('eight');
case 9
disp('nine');
case 10
disp('ten');
otherwise
disp('Error');
endYu Ting Luhttps://www.mathworks.com/matlabcentral/profile/authors/12181841-yu-ting-lutag:www.mathworks.com,2005:Question/4454892019-02-18T02:14:31Z2019-02-18T02:14:31ZContoured frequency by altitude diagramHi ! Im a meterology student and I want to ask how to do a contoured frequency by altitude diagram similar to this plot by Yuter and Houze 1995. They first did a histogram on a single level then stacked it like in the figure b then contoured it in figure c. Is there a way to stacked histogram similar to figure b?Noel Bangquiaohttps://www.mathworks.com/matlabcentral/profile/authors/12626364-noel-bangquiaotag:www.mathworks.com,2005:Question/4454872019-02-18T02:07:45Z2019-02-18T02:10:41ZVectorized rational approximation for e^x running slower than JIT compiler? I've timed the following methods of solving e^x and for some reason the vectorized code is taking longer than the JIT compiler. My direct calculation also seems to be slower than I would've expected. Is there a way to modify my code so the vectorized solution is faster?
n=10000000;
x=linspace(0,1,n);
c1=3/5;
c2=3/20;
c3=2/5;
c4=1/20;
y=0;
start_time=tic;
%%Serialized rational function approximation%%
for k=1:n
x2=x(k)*x(k);
y(k) = (1-c1*x(k)+c2*x2-(x(k)/60)*x2)/...
(1+c3*x(k)+c4*x2);
end % for k=1:n
elapsed_time1=toc(start_time);
fprintf('Computational time for serialized solution: %0.3f\n',elapsed_time1);
figure
plot(x,y,'linewidth',2.0,'color','r') % red thick line
axis([0 1 0 1]);
xlabel('\bf\fontsize{16} x');
ylabel('\bf\fontsize{16} y');
title(['\fontsize{16} Serialized rational function approximation to e^{-x} (Time: ',...
sprintf('%.3f',elapsed_time1) ')']);
legend('Serialized Calculation');
print serialized_rational_approximation.jpg -djpeg
%%JIT rational function approximation%%
start_time=tic;
% allocate space for y and initialize as 0?s
y=zeros(1,n);
for i=1:n
x2=x(i)*x(i);
y(i) = (1-c1*x(i)+c2*x2-(x(i)/60)*x2)/...
(1+c3*x(i)+c4*x2);
end % for i=1:n
elapsed_time2=toc(start_time);
fprintf('Computational time for JIT solution: %0.3f\n',elapsed_time2);
figure
plot(x,y,'linewidth',2.0,'color','g') % thick line, green is default
axis([0 1 0 1]);
xlabel('\bf\fontsize{16} x');
ylabel('\bf\fontsize{16} y');
title(['\fontsize{16} JIT rational function approximation to e^{-x} (Time: ',...
sprintf('%.3f',elapsed_time2) ')']);
legend('JIT Calculation');
print JIT_rational_approximation.jpg -djpeg
%%Vectorized rational functional approximation%%
start_time=tic;
y=(1-c1.*x+c2.*(x.^2)-(x.^3)./60)./(1+c3.*x+c4.*(x.^2));
elapsed_time3=toc(start_time);
fprintf('Computational time for vectorized solution: %0.3f\n',elapsed_time3);
figure
plot(x,y,'linewidth',2.0,'color','b') % thick line, green is default
axis([0 1 0 1]);
xlabel('\bf\fontsize{16} x');
ylabel('\bf\fontsize{16} y');
title(['\fontsize{16} Vectorized rational function approximation to e^{-x} (Time: ',...
sprintf('%.3f',elapsed_time3) ')']);
legend('Vectorized Calculation');
print vectorized_rational_approximation.jpg -djpeg
%%Direct Calculation%%
start_time=tic;
y=exp(-x);
elapsed_time4=toc(start_time);
fprintf('Computational time for direct solution: %0.3f\n',elapsed_time4);
figure
plot(x,y,'linewidth',2.0, 'color', 'm') % thick line, green is default
axis([0 1 0 1]);
xlabel('\bf\fontsize{16} x');
ylabel('\bf\fontsize{16} y');
title(['\fontsize{16} Direct calculation of e^{-x} (Time: ',...
sprintf('%.3f',elapsed_time4) ')']);
legend('Direct Calculation');
print direct_calculation.jpg -djpegShayla Scotthttps://www.mathworks.com/matlabcentral/profile/authors/11960839-shayla-scotttag:www.mathworks.com,2005:Question/4454362019-02-17T17:40:33Z2019-02-18T01:52:38ZWrite a MATLAB function MyTrapezoid Xiang Chenhttps://www.mathworks.com/matlabcentral/profile/authors/13513717-xiang-chen