https://jp.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — 新規の質問2021-05-08T10:12:26Ztag:jp.mathworks.com,2005:Question/8249302021-05-08T09:52:18Z2021-05-08T10:12:26ZUnrecognized function or variable 'steg_lsb_enc'.subplot(2,1,1)
imshow(imread('C:\Users\Monster\Desktop\Network Security homework\jesse pinkman.jpg'))
title('sifrelenecek resim')
subplot(2,1,2)
imshow(imread('C:\Users\Monster\Desktop\Network Security homework\walter white.jpg'))
title('orjinal resim')
[enc_img]= steg_lsb_enc('walter white.jpg', 'jesse pinkman.jpg', 2);
subplot(2,1,1)
imshow(imread('walter white.jpg'))
title('orjinal resim')
subplot(2,1,2)
imshow(enc_img)
title('icinde sifre bulunan goruntu')
[enc_img]=steg_lsb_enc('walter white.jpg', 'jesse pinkman.jpg', 7);
subplot(2,1,1)
imshow(imread('walter white.jpg'))
title('orjinal resim')
subplot(2,1,2)
imshow(enc_img)
title('icinde sifre bulunan goruntu')Mert Aydinhttps://jp.mathworks.com/matlabcentral/profile/authors/20123439tag:jp.mathworks.com,2005:Question/8249552021-05-08T10:08:26Z2021-05-08T10:08:26ZPlot max value in a curveHi
I have the following simple code and I want to plot the maximum point for each curve on the graph
appreicate your help
Thanks
AHMED FAKHRIhttps://jp.mathworks.com/matlabcentral/profile/authors/5718026tag:jp.mathworks.com,2005:Question/8249502021-05-08T10:08:15Z2021-05-08T10:08:15ZIndex in position 1 exceeds array bounds (must not exceed 1).error in SVM when i run this code ,it shows like Index in position 1 exceeds array bounds (must not exceed 1).error in line 208
TrainingSet=[ DF(1,:);DF(2,:);DF(3,:);DF(4,:);DF(5,:);DF(6,:);DF(7,:);DF(8,:);DF(9,:);DF(10,:);DF(11,:);DF(12,:);...
DF(13,:);DF(14,:);DF(15,:);DF(16,:);DF(17,:);DF(18,:);DF(19,:);DF(20,:);DF(21,:);DF(22,:);DF(23,:);DF(24,:);...
DF(25,:);DF(26,:);DF(27,:);DF(28,:);DF(29,:);DF(30,:);DF(31,:);DF(32,:);DF(33,:);DF(34,:);DF(35,:);DF(36,:);...
DF(37,:);DF(38,:);DF(39,:);DF(40,:);DF(41,:);DF(42,:);DF(43,:);DF(44,:);DF(45,:);DF(46,:);DF(47,:);DF(48,:);DF(49,:);DF(50,:) ]
how to slove that ,please help through code.
clc
clear all
close all
cd segmented_images
DF=[]
for i=1:50
i
str1=int2str(i)
str2=strcat(str1,'.jpg');
rgbImage=imread(str2);
%%[filename, pathname] = uigetfile({'*.*';'*.bmp';'*.jpg';'*.gif'}, 'Pick a Leaf Image File');
%%rgbImage = imread([pathname,filename]);
rgbImage = imresize(rgbImage,[256,256]);
bplane= rgbImage(:,:,3) - 0.5*( rgbImage(:,:,1)) - 0.5*( rgbImage(:,:,2));
%figure
%imshow(bplane)
%Extract out purple cells
%figure
BW= bplane >29;
%imshow(BW)
%%Remove noise 100 pixels or less
BW2=bwareaopen(BW,350);
%subplot(2,4,6);imshow(BW2);
%title('WBC Dilated Image');
%%calculate area of regions
%cellStats = regionprops(BW2, 'all');
%cellAreas = [cellStats(:).Area];
%%Superimpose onto original image
%figure,imshow(image),hold on
%himage=imshow(BW2);
%set(himage, 'AlphaData', 0.5);
CC= bwconncomp(BW2);
count = CC.NumObjects;
stats=regionprops(CC,'Area','Circularity','Centroid','Eccentricity','EquivDiameter','Extent','FilledArea','Perimeter','MajorAxisLength','MinorAxisLength','Image','Solidity');
%Centroid=reshape([stats.Centroid],2,CC.NumObjects)
majors=[stats.MajorAxisLength];
minors=[stats.MinorAxisLength];
Area=[stats.Area]
Circularity =[stats.Circularity]
Perimeter=[stats.Perimeter]
diameters=[stats.EquivDiameter]
radii=[diameters./2]
%image compression using DCT
% Convert to grayscale if image is RGB
if ndims(rgbImage) == 3
img = rgb2gray( rgbImage);
end
%figure, imshow(img); title('Gray Scale Image');
%img = rgb2gray(seg_img)
J=dct2(img);
%imshow(log(abs(J)),[]);
%colormap parula
%colorbar
J(abs(J)<10) =0;
K= idct2(J);
K=rescale(K);
%subplot(2,4,5);imshow(K);
%montage({I,K})
%title('Compressed Image');
% Create the Gray Level Cooccurance Matrices (GLCMs)
glcms = graycomatrix(K);
% Derive Statistics from GLCM
stats = graycoprops(glcms,'Contrast Correlation Energy Homogeneity');
Contrast = stats.Contrast
Correlation = stats.Correlation
Energy = stats.Energy
Homogeneity = stats.Homogeneity
Mean = mean2(rgbImage)
Standard_Deviation = std2(rgbImage)
Entropy = entropy(rgbImage)
%RMS = mean2(rms(rgbImage));
%Skewness = skewness(rgbImage)
Variance = mean2(var(double(rgbImage)))
a = sum(double(rgbImage(:)));
Smoothness = 1-(1/(1+a))
Kurtosis = kurtosis(double(rgbImage(:)))
Skewness = skewness(double(rgbImage(:)))
% Inverse Difference Movement
m = size(rgbImage,1);
n = size(rgbImage,2);
in_diff = 0;
for i = 1:m
for j = 1:n
temp = rgbImage(i,j)./(1+(i-j).^2);
in_diff = in_diff+temp;
end
end
IDM = double(in_diff)
WBC_COUNT=count
FEAT = horzcat(1,[Contrast Correlation Energy Homogeneity Mean Standard_Deviation Entropy Variance Smoothness Kurtosis Skewness IDM diameters radii Area Circularity Perimeter]);
DF=[DF,FEAT];
end
cd ..
inp=input('enter image:')
rgbImage=imread(inp);
%[filename, pathname] = uigetfile({'*.*';'*.bmp';'*.jpg';'*.gif'}, 'Pick a wbc Image File');
%rgbImage = imread([pathname,filename]);
%rgbImage = imresize(rgbImage,[256,256]);
% [rows columns numberOfColorBands] = size(rgbImage);
% Enlarge figure to full screen.
%set(gcf, 'Position', get(0,'Screensize'));
bplane= rgbImage(:,:,3) - 0.5*( rgbImage(:,:,1)) - 0.5*( rgbImage(:,:,2));
%figure
%imshow(bplane)
%Extract out purple cells
%figure
BW= bplane >29;
%imshow(BW)
%%Remove noise 100 pixels or less
BW2=bwareaopen(BW,350);
%subplot(2,4,6);imshow(BW2);
%title('WBC Dilated Image');
%%calculate area of regions
%cellStats = regionprops(BW2, 'all');
%cellAreas = [cellStats(:).Area];
%%Superimpose onto original image
%figure,imshow(image),hold on
%himage=imshow(BW2);
%set(himage, 'AlphaData', 0.5);
CC= bwconncomp(BW2);
count = CC.NumObjects;
stats=regionprops(CC,'Area','Circularity','Centroid','Eccentricity','EquivDiameter','Extent','FilledArea','Perimeter','MajorAxisLength','MinorAxisLength','Image','Solidity');
%Centroid=reshape([stats.Centroid],2,CC.NumObjects)
majors=[stats.MajorAxisLength];
minors=[stats.MinorAxisLength];
Area=[stats.Area]
Circularity =[stats.Circularity]
Perimeter=[stats.Perimeter]
diameters=[stats.EquivDiameter]
radii=[diameters./2]
%image compression using DCT
% Convert to grayscale if image is RGB
if ndims(rgbImage) == 3
img = rgb2gray( rgbImage);
end
%figure, imshow(img); title('Gray Scale Image');
%img = rgb2gray(seg_img)
J=dct2(img);
%imshow(log(abs(J)),[]);
%colormap parula
%colorbar
J(abs(J)<10) =0;
K= idct2(J);
K=rescale(K);
%subplot(2,4,5);imshow(K);
%montage({I,K})
%title('Compressed Image');
% Create the Gray Level Cooccurance Matrices (GLCMs)
glcms = graycomatrix(K);
% Derive Statistics from GLCM
stats = graycoprops(glcms,'Contrast Correlation Energy Homogeneity');
Contrast = stats.Contrast
Correlation = stats.Correlation
Energy = stats.Energy
Homogeneity = stats.Homogeneity
Mean = mean2(rgbImage)
Standard_Deviation = std2(rgbImage)
Entropy = entropy(rgbImage)
%RMS = mean2(rms(rgbImage));
%Skewness = skewness(img)
Variance = mean2(var(double(rgbImage)))
a = sum(double(rgbImage(:)));
Smoothness = 1-(1/(1+a))
Kurtosis = kurtosis(double(rgbImage(:)))
Skewness = skewness(double(rgbImage(:)))
% Inverse Difference Movement
m = size(rgbImage,1);
n = size(rgbImage,2);
in_diff = 0;
for i = 1:m
for j = 1:n
temp = rgbImage(i,j)./(1+(i-j).^2);
in_diff = in_diff+temp;
end
end
IDM = double(in_diff)
WBC_COUNT=count
QF = horzcat(1,[Contrast Correlation Energy Homogeneity Mean Standard_Deviation Entropy Variance Smoothness Kurtosis Skewness IDM diameters radii Area Circularity Perimeter]);
%multi svm
TrainingSet=[ DF(1,:);DF(2,:);DF(3,:);DF(4,:);DF(5,:);DF(6,:);DF(7,:);DF(8,:);DF(9,:);DF(10,:);DF(11,:);DF(12,:);...
DF(13,:);DF(14,:);DF(15,:);DF(16,:);DF(17,:);DF(18,:);DF(19,:);DF(20,:);DF(21,:);DF(22,:);DF(23,:);DF(24,:);...
DF(25,:);DF(26,:);DF(27,:);DF(28,:);DF(29,:);DF(30,:);DF(31,:);DF(32,:);DF(33,:);DF(34,:);DF(35,:);DF(36,:);...
DF(37,:);DF(38,:);DF(39,:);DF(40,:);DF(41,:);DF(42,:);DF(43,:);DF(44,:);DF(45,:);DF(46,:);DF(47,:);DF(48,:);DF(49,:);DF(50,:) ]
GroupTrain={'1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '2' '2' '2' '2' '2' '2' '2' '2' '2' '2'...
'3' '3' '3' '3' '3' '3' '3' '3' '3' '3' '4' '4' '4' '4' '4' '4' '4' '4' '4' '4' '5' '5' '5' '5' '5' '5' '5' '5' '5' '5'}
TestSet=QF
SVMModels=cell(5,1);
Y=GroupTrain
classes=unique(Y);
rng(1);%for reproducibility
for j=1:numbe1(classes)
indx=strcmp(Y',classes(j)); %create binary classes for each classifier
SVMModel{i}=fitcsvm(DF,indx,'ClassNames',[false true],'Standardize',true,...
'KernelFunction','rbf','BoxContraint',1);
end
XGrid=QF;
for j=1:nume1(classes)
[~,Score] = predict(SVMMOdels{j},XGrid);
Scores(:,j)=Score(:,2);% second column contains positive class score
end
[~,maxScore]=max(Scores,[],2);
result=maxScore;
figure,imshow(rgbImage)
title ('input image')
if result==1
msgbox('Neutrophil')
elseif result==2
msgbox('Eosinophil')
elseif result==3
msgbox('Monocyte')
elseif result==4
msgbox('Lymphocyte')
elseif result==5
msgbox('Basophil')
end
Keerthi Dhttps://jp.mathworks.com/matlabcentral/profile/authors/18833241tag:jp.mathworks.com,2005:Question/8246702021-05-07T23:44:32Z2021-05-08T10:01:29ZHow to save part of the data in text file?I have the following plots at different time steps, I would like to save the data at the last time step in a text file. How can I simply do that?
For example my plotting section, I am saving the data into a multi-dimenional array that has the 3rd dim as t and would plot my data in three different timesteps. How can I save data in a text file at timestep 0.12 at the plots example and not the entire data.
Code:
t = 0;
step = 0;
hstep = 1;
wstep = 1;
while t < tend && step < N_max
[U_T, t] = MacCormack(U_T, gamma, t, dx, CFL, sigmma);
step = step + 1;
if mod(step,wstep) == 0
U_TData(:,:,hstep) = U_T; % How to save this data in text file?
Vp_Data(:,:,hstep) = C2P( U_T, gamma );
hstep = hstep+1;
t_Data(hstep) = t;
end
end
shiste = size(U_TData);
numframe = shiste(3);
iterframe = floor(numframe/3);
f1 = figure();
subplot(2,2,1)
for i = 1:3
plot(x,U_TData(1,:,i*iterframe))
hold on
Legend{i} = strcat('t=', num2str(t_Data(i*iterframe),'%.2f'));
end
Plots:
Lujain Almarhabihttps://jp.mathworks.com/matlabcentral/profile/authors/12080112tag:jp.mathworks.com,2005:Question/8230802021-05-06T11:11:20Z2021-05-08T10:00:23ZNeed help with Turbo product codeI am trying to encode a grsy image using turbo product code but it's not working. The code I tried is below:
clc
clear
N = [127;255];
K = [120;239];
img = imread('pout.tif');
img = de2bi(img);
resized = imresize(img,[prod(K) 1]);
enc = tpcenc(resized,N,K);
enc = double(enc);
dec = tpcdec(enc,N,K);
op_img = reshape(dec,[],8);
op_img = op_img.';
op_img = reshape(2.^(0:7)*op_img,[],15);
op_img = imresize(op_img,[290 240]);
op_img = uint8(op_img);
figure();imshow(op_img)
Can you please guide me with this?Neeraj Chimwalhttps://jp.mathworks.com/matlabcentral/profile/authors/12637151tag:jp.mathworks.com,2005:Question/8249452021-05-08T09:59:34Z2021-05-08T09:59:34ZNOT GETTING CORRECT PHI{I} VALUEHello everyone,
I am trying to obtain equations of phi. I am getting wrong value of phi{3}. There is somthing wrong, which I am unable to figure out.
here is code:
clc
clear all;
initial_function=@(x,y)x.^2;
m=3;
for i=1:m;
r=floor(sqrt(i-1));
t=i-1-r.^2;
if t/2==0;
s=t/2;
fm{i}=@(x,y)(x.^r).*(y.^s)
else
s=(t-1)/2;
fm{i}=@(x,y)(x.^s).*(y.^r);
end
end
for i=1:1
phi{i}=@(x,y)fm{1}(x,y).*initial_function(x,y);
end
xmin=@(y) y;
syms x y;
for i=2:m
phi{i}=@(x,y)fm{i}(x,y).*phi{1}(x,y);
% null{i}=@(x,y)0;
for j=1:i-1;
a{i}{j} = integral2(@(y,x)fm{i}(x,y).*phi{1}(x,y).*phi{j}(x,y),0,1,xmin,1)./integral2(@(y,x)phi{j}(x,y).*phi{j}(x,y),0,1,xmin,1);
% null{i}{j}=a{i}{j}*phi{j}(x,y)
% null{i}= @(x,y)null{i}(x,y)+ a{i}{j}*phi{j}(x,y)
phi{i}=@(x,y)phi{i}(x,y)-a{i}{j}.*phi{j}(x,y);
% i
% j
% null1{j}=null{j}(x,y)
% phi2{j}=phi{i}(x,y)
% phi{i}=@(x,y)phi{i}(x,y)-null{i}{j};
end
% phi{i}=@(x,y)phi{i}(x,y)-a{i}{j}*phi{i}(x,y);
% phi{i}=@(x,y)phi{i}(x,y)-null{i}(x,y);
phi1{i}=phi{i}(x,y);
end
phi{1} and phi{2} are correct.
phi{3} which i am getting from matlab is: x^2*y - (29645651611899925216907*x^2)/81129638414606681695789005144064 - (4503599623397961*x^3)/9007199254740992
while correct phi{3} is: x^2*y- 3.328*10^(-3) - 0.504x^3.
I shall be very thankful if somone can help.nikhil maharhttps://jp.mathworks.com/matlabcentral/profile/authors/17302444tag:jp.mathworks.com,2005:Question/8249402021-05-08T09:58:53Z2021-05-08T09:58:53Zerror in mdl/rsquared.ordniaryHi,
I am trying to use fitlm and rsquared ordinary functions and I can't figure out where the errors comes from.
Moreover, I want to plots 3 graphs but only the first one appears.
I would really appreciate your help.
here is my code :
function[]=reaction_order(A)
fit0=A;
fit1=log(A);
fit2=1./A;
time=[1:11]';
f0=fit(time,fit0','poly1');
figure
plot(f0,time,fit0);
xlabel('Time [s]');
ylabel('A [M]')
title('Zero order fit, A concentration as a function of time')
legend('A concentration', 'Fit curve')
mdl0=fitlm(time,f0);
rsquared0=mdl0.Rsquared.ordinary;
fprintf(rsquared0)
f2=fit(time,fit2','poly1');
figure;
plot(f2,time,fit2);
xlabel('Time [s]');
ylabel('1/A [1/M]')
title('Second order fit, 1/A as a function of time')
legend('1/A', 'Fit curve')
mdl2=fitlm(time,f2);
rsquared2=mdl2.Rsquared.ordinary;
The error is :
Error using classreg.regr.FitObject/assignData (line 134)
Predictor and response variables must have the same length.
Error in classreg.regr.TermsRegression/assignData (line 245)
model =
assignData@classreg.regr.ParametricRegression(model,X,y,w,asCat,varNames,excl);
Error in LinearModel.fit (line 1030)
model =
assignData(model,X,y,weights,asCatVar,dummyCoding,model.Formula.VariableNames,exclude);
Error in fitlm (line 121)
model = LinearModel.fit(X,varargin{:});
Error in chimieq2>reaction_order (line 50)
mdl0=fitlm(time,f0);
Error in chimieq2 (line 4)
reaction_order(A)Noa Prasquierhttps://jp.mathworks.com/matlabcentral/profile/authors/21741252tag:jp.mathworks.com,2005:Question/8247852021-05-08T04:23:47Z2021-05-08T09:57:54ZError using odearguments line doesn't exist.[T,Y] = ode45(@Bqfun1,[0 2],[1 1 -0.01]);
plot (T,Y(:,1),'b','linewidth',1)
function dy1 = Bqfun1(t,y)
dy1 = zeros(2,1);
dy1=[y(2)];
y(3)
-3*y(3)-3*y(2)-y(1)-4*sin(t);
end
Error using odearguments (line 95)
BQFUN1 returns a vector of length 1, but the length of initial conditions vector is 3. The vector returned by BQFUN1 and
the initial conditions vector must have the same number of elements.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in Test4 (line 1)
[T,Y] = ode45(@Bqfun1,[0 2],[1 1 -0.01]);
What the heck does this even mean? I dont have a line 95.David Scidmorehttps://jp.mathworks.com/matlabcentral/profile/authors/19257228tag:jp.mathworks.com,2005:Question/8244052021-05-07T15:54:16Z2021-05-08T09:57:41ZError using ode45Trying to solve this functions but it give me this error.
global m g r I ks
m = 5;
g = 9.81;
r = 0.470;
I = 0.37;
ks = 0.012;
dt = 0.01;
tspan = (0:dt:5);
x0 = [0,0];
[t,x] = ode45(funcionMAT,tspan,x0);
plot(t,x(:,1));
plot(t,x(:,2));
a = x(2)-x(1)/dt;
plot(t,a);
Error
Attempt to execute SCRIPT funcionMAT as a function:
D:\Users\Javier E. Negron\Documents\Trabajos de universidad (ene-may 2021)\Capstone\funcionMAT.m
Error in Analisis_de_movimiento2 (line 13)
[t,x] = ode45(funcionMAT,tspan,x0);Javier Negronhttps://jp.mathworks.com/matlabcentral/profile/authors/19743268tag:jp.mathworks.com,2005:Question/8245002021-05-07T17:59:08Z2021-05-08T09:55:05ZAdapt RK4 ODE Solver from first order to 2nd orderI have a Matlab function for doing Runge-Kutta4k approximation for first-order ODE's, and I want to adapt it to work for second-order ODE's. This is what I have for first order RK4 ( and it's not working x) ) Would anyone be able to help me find a solution ?
function yt = RK4_2ndOrder(dxdt,y0,h,tfinal)
yt = zeros(2,length(h:tfinal)); %Memory Allocation
yt(:,1) = y0; %Initial condition
i = 2;
for t = h : h : tfinal %RK4 loop
k1 = dxdt(t-h,yt(:,i-1));
k2 = dxdt(t - (0.5*h), yt(:,i-1) + 0.5*k1*h);
k3 = dxdt(t - (0.5*h), yt(:,i-1) + 0.5*k1*h);
k4 = dxdt(t, yt(:,i-1) + (k3 * h));
yt(:,i) = yt(:,i-1) + (1/6 * (k1 + 2*k2 + 2*k3 + k4)* h);
i = i + 1;
end
end
This is my main
clc;
clear;
h = 0.01; %Time step
y0 = 1; %Initial condition dx1/dt = 1 m.s
tfinal = 20;
tarray = 0:h:tfinal;
ytRK4 = RK4(@dxdt,y0,h,tfinal);
plot(tarray,ytRK4_2ndOrder,'g');
And my function
function dx = dxdt(t,x)
m1 = 12000;
m2 = 10000;
m3 = 8000;
k1 = 3000;
k2 = 2400;
k3 = 1800;
dx = [ x(4) ; x(5) ; x(6) ; -k1/m1*x(1)+k2/m1*(x(2)-x(1)) ; k2/m2*(x(1)-x(2))+k3/m2(x(3)-x(2)) ; k3/m3*(x(2)-x(3)) ];
end
When I try to run my program, it says "Index exceeds the number of array elements" and "Error in dxdt (line 8)
dx = [x(4);x(5);x(6);-k1/m1*x(1)+k2/m1*(x(2)-x(1));k2/m2*(x(1)-x(2))+k3/m2(x(3)-x(2));k3/m3*(x(2)-x(3))];". As a beginner on Matlab, I don't really understand what that means...
Thanks in advance for the help !Nicolas Carohttps://jp.mathworks.com/matlabcentral/profile/authors/22470281tag:jp.mathworks.com,2005:Question/8249352021-05-08T09:54:51Z2021-05-08T09:54:51ZDCC MIDAS X modelwith the reference of Professor Han Qian's dcc midas code, it can only analysis the correlation of two series but not include "x" which is low-frequency macro variable. The input arguments of DccMidas doesn't include "x", the macro economic variables, so is there any method to do the Dcc-midas fitting with macroeconomic variables. How can the macro variables be included in the model?Nan Wanghttps://jp.mathworks.com/matlabcentral/profile/authors/20725761tag:jp.mathworks.com,2005:Question/8239902021-05-07T08:46:17Z2021-05-08T09:51:52ZGet all used variable names from a scriptAs in the check "Check usage of restricted variable names" I want to check the names of variables used in a script, only against our more explicit naming conventions. But using symvar also returns keywords like "function", "if" or "end" and also, what is much worse, any word found in comments and even "-delimited strings. Is there any function that can return me all variable names used in a script file or string, but nothing else?
Or to be a bit more precise, as Stephen Cobeldick correctly hinted to the dynamic execution nature of scripting languages: variable names, that are explicitly used in a function header as input or output variables (not varargin, varargout), and variable names explicitly used as left hand arguments in assignments like a = <some expression> or [a, b] = <expression>. That certainly would be sufficient, as the execution context here is eml, so apart from local variables data flow is pretty much under control with signal i/o and data store memory requiring registration as Stateflow.Data objects.Roberthttps://jp.mathworks.com/matlabcentral/profile/authors/84560tag:jp.mathworks.com,2005:Question/2976152016-07-29T05:28:08Z2021-05-08T09:48:21ZHow to generate random graph of n vertices with random connections in matlabHi I am interested in creating random undirected graph with n vertices and with random connections. This generated graph has to display its adjacency connections in a nxn matrix.I have tried this code but it is not working for my requirement.
n=input('No. of vertices')
c=input('Random connections')
MM=0; %arbitrary starting value
all_nums=1:n;
while MM ~=n*c
M = sparse([],[],[],n,n,n*c);
ctin = zeros(1,n);
for ii=1:n
noconnect=ctin>=c;
noconnect(ii)=true;
rem_nums = all_nums(~noconnect); % remaining numbers
rp=randperm(n-sum(noconnect));
rp = rem_nums(rp); % remaining numbers, hussled
if numel(rp)<c
break
else
r=rp(1:c);
end
M(ii,r)=1;
ctin(r)=ctin(r)+1;
end
MM=sum(ctin);
end
end
A= adjacency(M)SIVAKUMAR Vhttps://jp.mathworks.com/matlabcentral/profile/authors/7719405tag:jp.mathworks.com,2005:Question/2250392015-06-23T22:41:27Z2021-05-08T09:47:48ZHow can I make matrix name and value in one matrixI have several value with individual name for each. How can I bring all of them in one matrix that first column is value and second column is name.
I have:
A = 6;
B= 7;
C = 3;
D = 5;
I want:
Z = [6,A;7,B;3,C;5,D];Moehttps://jp.mathworks.com/matlabcentral/profile/authors/4742713tag:jp.mathworks.com,2005:Question/8214252021-05-04T15:37:27Z2021-05-08T09:47:35ZWhat is the reference magnitude/amplitude for calculating dB in the power colorbar using STFT?When plotting a STFT of a signal, the colorbar on the right shows power density in dB. What is the reference magnitude/amplitude for calculating dB in the power then?
spectrogram(x,120,100,120,fs,'yaxis');Jan Alihttps://jp.mathworks.com/matlabcentral/profile/authors/17449316tag:jp.mathworks.com,2005:Question/4889362019-11-03T10:19:16Z2021-05-08T09:45:41ZLive Editor - Font and Background ColorHi There,
I would like to know if there is a way to change the default font for Text and Code as well as the background color of the Live Editor?
Cheers,
Benny Benjamin Rähmerhttps://jp.mathworks.com/matlabcentral/profile/authors/6575673tag:jp.mathworks.com,2005:Question/8249002021-05-08T09:01:47Z2021-05-08T09:41:21ZHow to draw lines on some part of defect segmented image.Hi, I want to draw two lines on image automatically. For your reference I have drawn those lines manually marked with green and violet colors using imline function as shown in matlab. Can anyone help me in this. Any help is much appreciated!!kanika bhallahttps://jp.mathworks.com/matlabcentral/profile/authors/19403324tag:jp.mathworks.com,2005:Question/8249252021-05-08T09:39:39Z2021-05-08T09:40:41ZChanging Keyboard shortcuts in App Designer in MacOSHello everyone,
I am am trying to change the keyboard shortcuts in App Designer in MacOS. More specifically I want to assing the Windows version shortcuts to Home and End keys, i.e. go to begginning/end of the line when pressed. I already changed the DefaultKeyBinding.dict file and in all the other programs Home and End keys work as expected but only in APP Designer they donot work, i.e. when pressend the cursor is sent to the end or beginning of the file, not the line. Anyone was able to change the shortcuts?
Thanks,
A.Aytac Alparslanhttps://jp.mathworks.com/matlabcentral/profile/authors/21352811tag:jp.mathworks.com,2005:Question/8244302021-05-07T16:11:59Z2021-05-08T09:39:59Zerror handling for complex equationHey,
My problem is that there is an error message to Laguerrsche, firstly because of a matrix multiplication and secondly that the second input of n over k has to be non negative. However, the input is at most 0, since k runs to pc-1. And all values are scalar, if then possibly the r value would be a vector. I see therefore no solution for the indicated problems and thank you in advance for the answer(s).
% Define the fibre characteristics and wavelength
nCore = 1.434;
nCladding = 1.42;
wavelength = 1.23; % microns
coreRadius = 25; % microns(Mü-meter)
% Calculate fibre V number
V = (2*pi*coreRadius/wavelength)*sqrt(nCore^2-nCladding^2);
% Calculate wavenumber
k = 2 * pi / wavelength;
% Calculate Fleckradius
wf = sqrt(2*coreRadius^2/V);
iL=1;
pc =3;
r= [0,0.00001,0.005];
Laguerrsche = symsum(nchoosek(pc-1+iL,pc-1-k)*(-2*r.^2/wf^2)^k/factorial(k), k,0, pc-1);
YFeld= sqrt(factorial(pc-1)*pi/factorial(p-1+iL)) *1/wf* Laguerrsche*exp(-x^2/wf^2)*(sqrt(2)*x/coreRadius)^iL;
plot(r,YFeld)
Anna-Lena Gepperthttps://jp.mathworks.com/matlabcentral/profile/authors/15262578tag:jp.mathworks.com,2005:Question/8249202021-05-08T09:38:29Z2021-05-08T09:38:29ZWhat does function predict() in Deep Learning Toolbox do?Hi, I follow the example of this
https://www.mathworks.com/matlabcentral/answers/488935-how-can-i-apply-multiple-inputs-to-get-a-output-with-lstm
and made a little modification, namely by not using predict() function but calling predictAndUpdateState() to predict the target one by one.
In this way I get a much worse predition result (brown line) as predict() (yellow line).
Can anyone explain this?
The only different part is
% opt1: pure use feature variables as input
net = resetState(net);
YPred = [];
for i = 1:numel(XTest)
[net, temp] = predictAndUpdateState(net, XTest(:,i), 'ExecutionEnvironment', 'cpu');
YPred(:,i) = cell2mat(temp);
end
y1 = YPred;
Whole codes:
[~,~,data] = xlsread('ET_1.xlsx');
data_mat = cell2mat(data);
XTrain = (data_mat(:,4:8))';
XTrain = num2cell(XTrain,1);
YTrain = (data_mat(:,3))';
YTrain = num2cell(YTrain,1);
%%Define Network Architecture
featureDimension = size(XTrain{1},1);
numResponses = size(YTrain{1},1);
numHiddenUnits = 500;
layers = [ ...
sequenceInputLayer(featureDimension)
lstmLayer(numHiddenUnits,'OutputMode','sequence')
fullyConnectedLayer(500) %%50
dropoutLayer(0.1) %%0.5
fullyConnectedLayer(numResponses)
regressionLayer
];
maxepochs = 500;
miniBatchSize = 1;
options = trainingOptions('adam', ... %%adam
'MaxEpochs',maxepochs, ...
'GradientThreshold',1, ...
'InitialLearnRate',0.005, ...
'LearnRateSchedule','piecewise', ...
'LearnRateDropPeriod',125, ...
'LearnRateDropFactor',0.2, ...
'Verbose',0, ...
'Plots','training-progress');
%%Train the Network
net = trainNetwork(XTrain,YTrain,layers,options);
%% Test the Network
[~,~,data] = xlsread('ET_2.xlsx');
data_mat = cell2mat(data);
XTest = (data_mat(:,4:8))'; XTest = num2cell(XTest,1);
YTest = (data_mat(:,3))'; YTest = num2cell(YTest,1);
% opt1: pure use feature variables as input
net = resetState(net);
YPred = [];
for i = 1:numel(XTest)
[net, temp] = predictAndUpdateState(net, XTest(:,i), 'ExecutionEnvironment', 'cpu');
YPred(:,i) = cell2mat(temp);
end
y1 = YPred;
% opt2: predict()
net = resetState(net);
YPred = predict(net, XTest);
y2 = (cell2mat(YPred)); %have to transpose as plot plots columns
%%
figure; hold all
yRef = (cell2mat(YTest)');
plot(yRef, '-o')
plot(y1, '-x')
plot(y2, '-s')
Song Decnhttps://jp.mathworks.com/matlabcentral/profile/authors/10395652tag:jp.mathworks.com,2005:Question/8249152021-05-08T09:34:18Z2021-05-08T09:34:18ZHow to plot actual amplitude on the colorbar using STFT (spectrogram)I am using built in spectrogram function and it automatically plots the power/frequency (dB/Hz) values on the colorbar on the right.
Does anyone know how to plot actual amplitude/magnitude of a signal (A or V) on the colorbar using STFT (spectrogram)?
Thanks in advance,Jan Alihttps://jp.mathworks.com/matlabcentral/profile/authors/17449316tag:jp.mathworks.com,2005:Question/8146452021-04-27T13:17:55Z2021-05-08T09:33:36ZExtending regression lines beyond data spanHi everyone,
I'm working on a code that would predict Arctic ice coverage during the rest of the 21st century, like so:
%load ice coverage data
data = load('Ice_North.txt');
%define variables
year = data(:,1);
data_month(:,1:12) = data(:,2:13); %a new matrix with monthly values only
%calculate the yearly average time series
yearData = nanmean(data_month,2);
%plot yearly averaged time series
figure(1)
plot(year, yearData, 'LineWidth',2,'Color','b')
xlabel('Year')
ylabel('Sea ice coverage (milions of km^2)')
grid on
title('Annual average Arctic sea ice coverage')
%regression analysis
%linear
coeff1 = polyfit(year,yearData,1);
f1 = polyval(coeff1,year);
hold on
plot(year,f1,'LineWidth',1.5,'Color','r')
%quadratic
coeff2 = polyfit(year,yearData,2);
f2 = polyval(coeff2,year);
hold on
plot(year,f2,'LineWidth',1.5,'Color','g')
legend('Data','Linear interpolation','Quadratic interpolation')
I would like to extend both linear and quadratic interpolations, so that they reach up to, for example 2100. Any advice on how to do that?
All the best,
MajaMaja Zdulskahttps://jp.mathworks.com/matlabcentral/profile/authors/14081515tag:jp.mathworks.com,2005:Question/8246652021-05-07T23:38:15Z2021-05-08T09:31:55ZHelp indexing: How to index at the interfaces of cells and not the cellsI am struggling to understand how to setup some indexing problem in MATLAB. If my entire domain is defined from 1 to N with a padding of two cells. So say my internal domain (domain without padded cells) from 2 to N-2, then if I want to calculate some values at the "interfaces" of the cells instead at the cells, how can I setup this on MATLAB? For example I have the following code for the internal domain that I would like to change my indicies to the interfaces?
My set up is like:
% calculate Flux at j+1/2
%
% j+1/2 Cell's grid:
% | wL| |
% | /|wR | 1 2 3 4 N-2 N-1 N
% | / |\ | {x=0} |-o-|-o-|-o-|-o-| ... |-o-|-o-|-o-| {x=L}
% |/ | \ | 1 2 3 4 5 N-1 N N+1
% | | \|
% | | | NC: Here cells 1 and N are ghost cells%
% j j+1
I keep getting the error:
Index in position 2 exceeds array bounds
The code for example:
function [ U_L, U_R] = MUSCL(U,N,NEQ )
size_U = size(U);
U_L = zeros(size_U);
U_R = zeros(size_U);
delta = 1e-6; % epsilon
for i= 1:NEQ
for j = 3:N-1
denom_L = (U(i,j) - U(i,j-1));
denom_R = (U(i,j+2) - U(i,j+1)); % error here since index exceeds the bounds of the array N (1001 here)
denom_L = sign(denom_L+1e-64)*max(delta, abs(denom_L));
denom_R = sign(denom_R+1e-64)*max(delta, abs(denom_R));
r_L = (U(i,j) - U(i,j-1))/denom_L;
r_R = (U(i,j+2) - U(i,j+1))/denom_R;
theta_L = Limiter(r_L);
theta_R = Limiter(r_R);
end
end
for j = 2:N-2
U_L(:,j) = U(:,j)+0.5*theta_R.*(U(:,j)-U(:, j-1));
U_R(:,j) = U(:,j+1)-0.5*theta_L.*(U(:,j+2)-U(:,j+1));
end
end
How can I find U_L,U_R, r_L, r_R at j+1/2 ??Lujain Almarhabihttps://jp.mathworks.com/matlabcentral/profile/authors/12080112tag:jp.mathworks.com,2005:Question/8029362021-04-15T11:12:22Z2021-05-08T09:29:25ZGuassian Process Regression (fitrgp()): Setting KernelScale as a constant without specifying FitMethod as 'none'I'd like to set KernelScale as constant similar to how ConstantSigma can be specified; however, if I choose FitMethod='none', then Beta and other variables aren't analytically solved for. Assuming this isn't a theoretically unsound request, how do I set KernelParameters ( KernelScale and Sigma) as fixed?
Related: How to check the kernel parameter values of a Gaussian process regression (GPR) model after trainingSterling Bairdhttps://jp.mathworks.com/matlabcentral/profile/authors/12806163tag:jp.mathworks.com,2005:Question/3220802017-01-26T17:46:42Z2021-05-08T09:29:09ZHow can I fix this error - "Error using / Matrix dimensions must agree"I am trying to get values for y with T in the range 800 - 1100. the function I have called antoine works for single values but i get the error seen in the screen shot when i try to use the linspace command. Any idea how i can fix this?jenny orrisshttps://jp.mathworks.com/matlabcentral/profile/authors/9095294tag:jp.mathworks.com,2005:Question/8247902021-05-08T04:54:58Z2021-05-08T09:28:58ZCan you guys help write a code for my machine problemWrite a script that will prompt the user to input a number from 1 – 9 only and display the
figure below.
Sean Russell Basaenhttps://jp.mathworks.com/matlabcentral/profile/authors/21747220tag:jp.mathworks.com,2005:Question/3322242017-03-27T23:58:02Z2021-05-08T09:24:57ZIs it possible to install matlab in a docker image?I wanted to install my matlab in a docker image. Is that possible?Brando Mirandahttps://jp.mathworks.com/matlabcentral/profile/authors/2706824tag:jp.mathworks.com,2005:Question/8248552021-05-08T07:08:06Z2021-05-08T09:22:00ZReading particular column in one excel file and write it in new excel fileI trying to read perticular column in .xlsx file and write it in the new .xlsx file.
Kaviarasu Natarajhttps://jp.mathworks.com/matlabcentral/profile/authors/18164452tag:jp.mathworks.com,2005:Question/8228102021-05-06T07:55:40Z2021-05-08T09:21:39Zrotating spheres using euler anglesI have two spheres separated by a distance of 2.01 units in my animation and euler angles associated with them, I want to rotate the spheres around y axis continuously how can i do that?Rishabh Katiyarhttps://jp.mathworks.com/matlabcentral/profile/authors/15995916tag:jp.mathworks.com,2005:Question/8249102021-05-08T09:17:32Z2021-05-08T09:17:32ZRead particular column in .xlsx file and write in new .xlsx file.I have excel file "Basefile 1.xlsx" in that file Data are in Column (A,B,C,D,E,F,G,H) from that i need to Create new excel file(.xlsx) and then copy the data from the "Basefile.xlsx - Sheet 2 - Column A,B,E,G". Then pasted it to the new excel file "Newfile.xlsx - Sheet 1 - Column A,B,C"Kaviarasu Natarajhttps://jp.mathworks.com/matlabcentral/profile/authors/18164452tag:jp.mathworks.com,2005:Question/5373232020-05-29T09:59:31Z2021-05-08T09:16:06ZFrequency interpretation of wpspectrum I am currently working on an implementation of a wavelet-transformation.
The example has two sin-signals with 1024 Samples of 50 and 500 Hz. FS = 16 kHz, so fg = 8kHz. I am decomposing it with 8 levels, with a db4-wavelet manually by using cconv (circular convolution) with the wfilters of low and high filters of db4 and downsampling it after each convolution. So I get a 256 entry cell array (256 terminal nodes) with 4 entries per cell - works properly imo. So far so good.
Comparing this implementation to the wpdec function of MATLAB, it uses a normal convolution, which results to more values on each level of decomposition, which is fine because of the size of the filter (1024 + 8 (db4-length) -1 = 1033 / 2 = 516 values instead of 512 with cconv). This leads to 10 values for each terminal node on level 8.
Comparing the energy of both implementations, they both do have high energy values at subband 2 (31.25-62.5 Hz) and subband 25 ( around 800 Hz). However then plotting the Frequencies of wpspectrum with the result of wpdec leads to the correct frequencies at band 2 and band 16 (50 and 500), while I would think that it had to be 50 and 800 by the results of the energy. wpspectrum uses the following 3 steps:
Extract the wavelet packet coefficients corresponding to the terminal nodes. Take the absolute value of the coefficients.
Order the wavelet packet coefficients by frequency ordering.
Determine the time extent on the original time axis corresponding to each wavelet packet coefficient. Repeat each wavelet packet coefficient to fill in the time gaps between neighboring wavelet packet coefficients and create a vector equal in length to node 0 of the wavelet packet tree object.
I am calculating the teager-operations of the coefficients of the terminal nodes - these are absolute values
In my opinion they are already frequency ordered cause the 8 times low-pass filtered signal should be placed in subband 1 and so on.
I dont really know what is suggested here, but all subbands have exactly 4 values and as the input signal is stationary I don't see a need for gap-filling. Am I mistaken here?
However, wpspectrum results in finding the 500 Hz frequency and I have no idea how it is able to. What has to be done with the resulting cell array to detect the correct frequencies?
Thanks in advance. I can provide code for further investigation aswell.Kai Blumhttps://jp.mathworks.com/matlabcentral/profile/authors/7792815tag:jp.mathworks.com,2005:Question/8249052021-05-08T09:10:04Z2021-05-08T09:10:04ZSimulink does not work (Ubuntu 20.04)
These are the error messages when I open simulink on Matlab R2021a on my Ubuntu 20.04. I recently installed both the OS and MATLAB.
When I dismiss these messages and try creating a blank model, I get get another error:
Please advise. Thank you.
William Ebenezarajhttps://jp.mathworks.com/matlabcentral/profile/authors/17466081tag:jp.mathworks.com,2005:Question/8248752021-05-08T08:13:09Z2021-05-08T08:59:04ZRegarding Self-Paced Matlab CoursesI recently got a student license of MATLAB with my university email and found the courses really helpful. I seem to have unlimited access to courses categorized under "Getting Started" but the ones under "Core MATLAB", I will have free access until the expiry date.
I am not that advanced yet to enroll those courses other than MATLAB Fundamentals(almost done with it), but when I do want to start those courses later on, they will expire and I will not have free access anymore. I am aware that they can be bought later on, but as a student that many courses would be too expensive.
Will the courses stay free as long as I renew my student license? If not, is there any way I would be able to keep free access to those courses? Hrithik Baruahttps://jp.mathworks.com/matlabcentral/profile/authors/21605466tag:jp.mathworks.com,2005:Question/8235702021-05-06T18:51:01Z2021-05-08T08:56:59Zmerging two ode graphsI tried to merge two ode function but getting an error. The first ode ranges upto T and thereafter I want result of other ode.Susmita Pandahttps://jp.mathworks.com/matlabcentral/profile/authors/22046378tag:jp.mathworks.com,2005:Question/8247702021-05-08T04:06:27Z2021-05-08T08:50:36ZSimulation of differential equations with multiple variables. BiotechnologyI want to simulate those differential equations and compare them with the values of X, P, S
my error: Array indices must be positive integers or logical values.
Error in @(t,a)[(umax(1-(a(3)/pmax)^n))*a(1);-((umax(1-(a(3)/pmax)^n))*a(1))/(yxs);ypx*((umax(1-(a(3)/pmax)^n))*a(1))]
function pos = paramfun1(x,tspan)
umax = x(1);
ypx = x(2);
yxs = x(3);
pmax = x(4);
xt0 = x(0.05,47,0);
f = @(t,a) [(umax(1-(a(3)/pmax)^n))*a(1);-((umax(1-(a(3)/pmax)^n))*a(1))/(yxs);ypx*((umax(1-(a(3)/pmax)^n))*a(1))];
[~,pos] = ode45(f,tspan,xt0);
B = [0.05,0.07,0.15,0.25,0.32,0.42,0.6,0.93,1.3,1.57,1.75,1.9]';
S = [47,76,45,42,40,35,28,21,9,2,0]';
P = [0,1,2,4,6,11,17,23,34,41,42,42]';
t = [0,2,4,6,8,10,12,14,16,18,20,22]'
umax = 0.33;
ypx = 0.90;
yxs = 0.0343;
pmax = 122.22;
n = 1.88;
%a(1) = x
%a(2) = s
%a(3) = p
f = @(t,a) [(umax(1-(a(3)/pmax)^n))*a(1);-((umax(1-(a(3)/pmax)^n))*a(1))/(yxs);ypx*((umax(1-(a(3)/pmax)^n))*a(1))];
xt0 = [0.5,47,0];
[tspan,a] = ode45(f,[0 47],xt0);
plot(tspan,a(:,1),tspan,a(:,2),tspan,a(:,3),t,[B,S,P],'o-')
title('Modelado Matemático: Levenspiel')
xlabel('Tiempo en hrs')
ylabel('Biomasa (X), Sustrato (S),Producto (P)')
hold offAdam Andersonhttps://jp.mathworks.com/matlabcentral/profile/authors/22474442tag:jp.mathworks.com,2005:Question/4952512019-12-06T15:28:16Z2021-05-08T08:45:02ZFit Powerlaw to DataHi all!
I need to fit following Power Law to some experimental data.
y = C(B+x)^n
The data I have is as the following:
STRESS = [0.574, 367.364, 449.112, 531.087, 596.241, 649.097, 695.038, 737.173, 815.008];
STRAIN = [2.8746e-04, 0.00063, 0.0459, 0.0901, 0.1320, 0.1725, 0.2132, 0.2557, 0.3579];
The variables are x and y are STRAIN and STRESS respectively, and I would like estimates for C, B and n.
I'm not sure how to use the fitting tool for this kind of specific model.
Any ideas or suggestions would be greatly appreciated!
Thank you very much!
Tobias Brammingehttps://jp.mathworks.com/matlabcentral/profile/authors/6162721tag:jp.mathworks.com,2005:Question/656242013-03-03T04:29:54Z2021-05-08T08:40:58Zcurve fitting a power functionWrite a user-defined function that fits data points to a power function of the
form y=b*m.^x . Name the function [b,m] = powerfit(x,y), where the
input arguments x and y are vectors with the coordinates of the data points,
and the output arguments b and m are the constants of the fitted exponential
equation. Use powerfit to fit the data below. Make a plot that shows the data points and function
x 0.5 2.4 3.2 4.9 6.5 7.8
y 0.8 9.3 37.9 68.2 155 198
First thing I did was open up an mfile and create a script
function [b,m] = powerfit(x,y)
However here is where I get confused I know the outputs much match so the function must be of the form [b,m]=function
But as of now i'm not sure what that function is, so I moved on to the portion I know how to solve.
I then proceeded to fit the polynomial via the poly fit command.
p=polyfit(log(x),log(y),1)
p =
1.4934 1.8864
Here is where I need to use the powerfit function in order to find the coefficients b and m so I can plot the graph. what I would do after achieving b and m would be to solve for the equation using polyval, and plotting the graph.
I appreciate the help
BrandonBrandonhttps://jp.mathworks.com/matlabcentral/profile/authors/4035603tag:jp.mathworks.com,2005:Question/8248952021-05-08T08:34:41Z2021-05-08T08:34:41ZI couldn't update my matlab R2018a, the installation always fail with the following update logI'm only providing the last few logs.
...Need to touch: help/wavelet/gs/eqn1452265113.png
Need to replace: help/wavelet/ref/plotdt.html
Need to replace: help/wavelet/ug/advanced-use-of-objects.html
Need to replace: help/wavelet/ref/waveletanalyzer-app.html
Need to replace: help/wavelet/ref/dddtreecfs.html
Need to touch: help/wavelet/ug/eqn1267622637.png
Need to touch: help/wavelet/ug/eqn1279034948.png
Need to replace: help/wavelet/ref/wavsupport.html
Need to replace: help/wavelet/ref/wpcoef.html
Need to touch: help/wavelet/arrow_right.gif
Need to replace: help/wavelet/ref/dwt3.html
Need to touch: help/wavelet/ug/plcwt2.png
Need to touch: help/wavelet/ug/eqn1464962721.png
Need to touch: help/wavelet/gs/more_arrows.gif
Need to touch: help/wavelet/ug/wavemenu2.png
Need to replace: help/wavelet/functionlist-alpha.html
Need to replace: help/wavelet/ug/importing-and-exporting-from-graphical-tools.html
Installation failed [1]Namie Abuhttps://jp.mathworks.com/matlabcentral/profile/authors/22395670tag:jp.mathworks.com,2005:Question/8248902021-05-08T08:25:40Z2021-05-08T08:25:40Zhow to connect dc motor block with inverter suketu vaidyahttps://jp.mathworks.com/matlabcentral/profile/authors/19792981tag:jp.mathworks.com,2005:Question/8248852021-05-08T08:23:49Z2021-05-08T08:23:49ZPerformance-wise, should I create my App Interactively using app designer or code it from the startupFcn(app)?I am creating an application in MATLAB r2020b, which has a lot og UI elements (mainly uibuttons and uitextarea). I have a total of ~1000 elements organized in a gridlayout.
I am creating all the elements programatically in the startupFcn(app), but It takes a long time to open the app (~1 min).
Would it improve the perfomance of my app if I create all the elements interactively using app designer???C.S.https://jp.mathworks.com/matlabcentral/profile/authors/19846978tag:jp.mathworks.com,2005:Question/8248802021-05-08T08:22:54Z2021-05-08T08:22:54ZWhy parfor is slower than for when accessing 3-D array?I want to make my for loop run faster in a program that i use a 3-D array and by experimenting i came to the conclusion that when I access a 3-D array with parfor is slower than doing it in for, whereas when I run the same code but using a 2-D array the results are the opposite.
A small example is the following.
%Storing data on 3-D array with parfor
tic
parfor (i=1:100)
for (j=2:2134)
for(x=1:1000)
k(i,j,x)=100;
end
end
end
toc
Elapsed time is 319.463914 seconds.
%storing data on 3-D array with for
tic
for (i=1:100)
for (j=2:2134)
for(x=1:1000)
k(i,j,x)=100;
end
end
end
toc
Elapsed time is 25.601181 seconds.
%Storing Data in 2-D array with parfor
tic
parfor (i=1:1000)
for (j=2:2134)
for(x=1:1000)
k(i,j)=100;
end
end
end
toc
Elapsed time is 0.774042 seconds.
%Storing Data in 2-D array with for
tic
for (i=1:1000)
for (j=2:2134)
for(x=1:1000)
k(i,j)=100;
end
end
end
toc
Elapsed time is 3.060670 seconds.
I am running in with 4 workers when in parallel.
Why is this happening when I am using 3-D arrays and how can i solve it?Panagiotis Polyzogopouloshttps://jp.mathworks.com/matlabcentral/profile/authors/22469553tag:jp.mathworks.com,2005:Question/8248352021-05-08T06:54:41Z2021-05-08T08:09:58ZHaving an Error in ncread try to open a netcdf using matlab, when I used ncread it says "Error in ncread". I don't know what's the problem because when I asked my friend to open the same file with the same script as mine on his computer it works fine without error. I try to uninstall my matlab and reinstall with several different version but it doesn't solve the problem. Any solution to fix my problem? currently I'm using matlab 2020b version. Here is script code to open my netcdf file:
ncdisp('T_Maret2016.nc');
lon=ncread('T_Maret2016.nc','Longitude');
lat=ncread('T_Maret2016.nc','Latitude');
z=ncread('T_Maret2016.nc','Depth');
time=ncread('T_Maret2016.nc','MT');
and I attached an example of variable in my netcdf file.
audi rachmanhttps://jp.mathworks.com/matlabcentral/profile/authors/22473729tag:jp.mathworks.com,2005:Question/8248452021-05-08T07:00:51Z2021-05-08T08:01:14Zreinforcement learning algorithm that is deployed online on a time varying systemHello,
I asked a similar question https://www.mathworks.com/matlabcentral/answers/822700-reinforcement-learning-lqr-example-question?s_tid=srchtitle but I want to focus on a very specific part.
I am trying to program a reinforcement learning algorithm that has to learn and control a system at the same time. I have one year hourly load data that impact the system, and I want to design an agent that needs to learn and control for that specific year given that data.
My problem is it seems to me the training phase is isolated from the simulation phase, so it's not clear to me how can I make the system advance through time during the training phase, record the state variables, and continue to the deployement phase. So my system is characterized by 8760 matrices each for every year of the hour. I want to make sure that:
1) when I train my agent for each training step that passes it advances to a new hour, basically I want to make sure my system isn't getting to try two different things in the same hour. To achieve that, do I need to make the episode length 1 ?
2) I need to have a history profile of all the actions my agent took during the training time, and the state values. In the training stats I can only see the reward per episode. I can't see the actions my agent took, nor the corrosponding state values.
3) my confusion is the reset function, I don't want the environment to reset the states, it has to continue from the last values. But why am i forced to use a reset function?
I think as long as I have these three things, I should be able to deploy my system to actively learn for x many hours then control for 8760-x many hours. From the way I see in the toolbox, there doesn't seem to be a clear way to do that. Can someone clarify for me?
What I think I need to do is make my states global variables, so I can try to train for one hour only, then advance the system to next time iteration, and also store the action variable to an indexed global variable?hamad alduaijhttps://jp.mathworks.com/matlabcentral/profile/authors/7832547tag:jp.mathworks.com,2005:Question/3393052017-05-08T15:35:07Z2021-05-08T07:57:31ZHow to generate 3D surface or robot workspace?I have a 4 DOF robot with variables t1,t2,d3 and t4. I used linspace to generate values for the variables, and also I calculated the positions, resulting 90x90x90 matrices (for X, Y and Z). Now how could I do a work-space with this data? Obviously plot3 or surf does not work. I searched the answers and the one with example is no longer valid.
Can please help me with some examples or code?
l1=500;l2=600;l3=400;l4=191.03;
t1=linspace(-180,180,90)*pi/180;
t2=linspace(-90,90,90)*pi/180;
d3=linspace(-200,200,90);
t4=linspace(-180,180,90)*pi/180;
nt1=length(t1);
nt2=length(t2);
nd3=length(d3);
for i=1:nt1
for j=1:nt2
for k=1:nd3
xM(i,j,k)=round((-cos(t1(i)).*cos(t2(j))).*((d3(k) + l2 + l3 + l4)));
yM(i,j,k)= round((-cos(t2(j)).*sin(t1(i))).*(d3(k) + l2 + l3 + l4));
zM(i,j,k)=round((l1 - l4.*sin(t2(j)) - sin(t2(j)).*(d3(k) + l2 + l3)));
end
end
end
Clarifications:
- What is workspace of a robot? Forward kinematics uses the kinematic equations of a robot to compute the position of the end-effector from specified values for the joint parameters. The dimensions of the robot and its kinematics equations define the volume of space reachable by the robot, known as its workspace. Or, as Amid said: the space that the robot gripper can reach, all way around (visualize all the points that the robot could reach, giving us a 3D space).
- The workspace using these dimensions will be a sphere. Why? The robot is a spherical robot (with two rotary joints and one prismatic).
- The parameter t4 does not appear in the equations, it's just the orientation of the final element (end-effector), thus it does not influence the workspace.
- The values of the variable parameters (t1,t2,d3) are maximum. This does not happen in real life, due to mechanical restrictions or space consideration. Modifying these parameters with more realistic values will result in a sphere with cut off top and bottom. This is normal, and that's how it should look.
Thank you very much for the help! Cristina Magdahttps://jp.mathworks.com/matlabcentral/profile/authors/8475541tag:jp.mathworks.com,2005:Question/1243532014-04-03T15:16:56Z2021-05-08T07:56:50ZDoes fitrm & ranova support within subject models without between subject factorsI am trying to use fitrm and ranova (Matlab2014a) to run a repeated measures anova on a 2x2 within subjects design. I currently have 4 variables representing the responses for all subjects in each cell of the 2x2 design.
I do not wish to include a between subject factor but rmfit seems to require at least one.
The code I am using is as follows.
alpha_power = randn(24,4); % This is my data but lets generate it for now
t = table(alpha_power(:,1),alpha_power(:,2), alpha_power(:,3), alpha_power(:,4),'VariableNames',{'Y1','Y2','Y3','Y4'}); % Create a table storing the respones
within = table({'A';'A';'V';'V'},{'T';'S';'T';'S'},'VariableNames',{'Attention','TMS'}); % Create a table reflecting the within subject factors 'Attention' and 'TMS' and their levels.
rm = fitrm(t,'Y1-Y4','WithinDesign',within); % Here the code breaks.
fitrm seems to require terms in the model specification which reflect the predictor variables (e.g. 'Y1-Y4~Gender'), but these are automatically specified as between subject factors, I do not have between subject factors.
Is it possible to specify terms as within subject factors? Jimhttps://jp.mathworks.com/matlabcentral/profile/authors/3515805tag:jp.mathworks.com,2005:Question/8248702021-05-08T07:52:33Z2021-05-08T07:52:33ZHow do I allow the user to save all the images of the floorplans they've created?So far the code only allows me to save the last floor plan created, rather than all of them.
e.g. if the user inputs 2 floors, only the image of the second floor shows, if the user inputs 3 floors, only the image of the floor plan of floor 3 shows o the pdf etc.
code i use to collect the floor data:
for b=1:spaces % %
rectangle('Position',[X(floorPlan,b),Y(floorPlan,b),width(floorPlan,b),depth(floorPlan,b)],'FaceColor',[0 .5 .5]);
X_text = X + width/3;
Y_text = Y + height/2;
text(X_text,Y_text,num2str(b))
saveas(gcf, "floorPlan.png" ); %
end
code is use to print image of floor data on to a pdf report:
import mlreportgen.report.*
import mlreportgen.dom.*
R = Report('Building Spatial Model report','pdf');
open(R)
tp = TitlePage;
tp.Title = 'Building Spatial Model Report';
tp.Subtitle = 'Building Spatial Structure';
tp.Author = 'my name';
add(R,tp);
plot1 = Image ( "floorPlan.png" );
plot1.Width = "7in" ;
plot1.Height = "5in" ;
add (R, plot1);
plot2 = Image ( "floorplan.png" );
plot2.Width = "7in" ;
plot2.Height = "5in" ;
add (R, plot2);
close(R)AKhttps://jp.mathworks.com/matlabcentral/profile/authors/20822905tag:jp.mathworks.com,2005:Question/8248602021-05-08T07:39:10Z2021-05-08T07:50:08Zwhile implementing the above code, getting error at line 8 & 10 = error is the value assigned to variable might be unsed?while implementing the above code, getting error at line 8 & 10 = error is the value assigned to variable might be unsed. plz give a solution to this problemHemen Gogoihttps://jp.mathworks.com/matlabcentral/profile/authors/17803796tag:jp.mathworks.com,2005:Question/8248652021-05-08T07:43:26Z2021-05-08T07:43:26ZHow MATLAB predict function compute the Negated average binary losses?Hi,
I have an multiclass SVM (onevsall) classifier trained using the classification Learner App.
It was mentioned here :
https://www.mathworks.com/help/stats/classificationecoc.predict.html#bufel6_-NegLoss
that one of the output of the predict function is an array containing the Negated average binary losses: I want to know how these Negloss values has been computed, I tried to use the equation provided in the binary loss :
https://www.mathworks.com/help/stats/classificationecoc.predict.html#bufel6__sep_sharedBinaryLoss
but I didn't get the Negloss values. How can I compute these values ?
Thank you
Akram Awadhttps://jp.mathworks.com/matlabcentral/profile/authors/22462845tag:jp.mathworks.com,2005:Question/8218352021-05-05T03:57:06Z2021-05-08T07:19:41ZWhy do these two codes give different covariance matrices?1st code:
S =[ 0.6661 - 0.7458i 0.4210 - 0.9071i 1.0000 + 0.0000i;-0.9127 + 0.4086i -0.8429 + 0.5381i 1.0000 + 0.0000i;1.0000 + 0.0000i 1.0000 + 0.0000i 1.0000 + 0.0000i;-0.9127 - 0.4086i -0.8429 - 0.5381i 1.0000 - 0.0000i;0.6661 + 0.7458i 0.4210 + 0.9071i 1.0000 - 0.0000i];
Rmm=cov(S);
2nd code:
S =[ 0.6661 - 0.7458i 0.4210 - 0.9071i 1.0000 + 0.0000i;-0.9127 + 0.4086i -0.8429 + 0.5381i 1.0000 + 0.0000i;1.0000 + 0.0000i 1.0000 + 0.0000i 1.0000 + 0.0000i;-0.9127 - 0.4086i -0.8429 - 0.5381i 1.0000 - 0.0000i;0.6661 + 0.7458i 0.4210 + 0.9071i 1.0000 - 0.0000i];
Rmm= S*S'/length(S(1,:));
Sadiq Akbarhttps://jp.mathworks.com/matlabcentral/profile/authors/966774tag:jp.mathworks.com,2005:Question/8248502021-05-08T07:05:03Z2021-05-08T07:05:03Zspeeding up trainbr using more cpu cores or a gputrainbr is slow on my computer often taking an hour. I'm looking at ways to speed it up. I'm trying to figure out if the Parallel Toolbox would help. It seems to say it would allow me to use multiple cpu cores, but when I'm running trainbr training it already looks like it is using multiple cores. Anybody know about this?
I have a GPU available but I recall reading trainbr can't use a GPU, anybody know about this?
Thank you!Brenthttps://jp.mathworks.com/matlabcentral/profile/authors/5323111