Tag Archives: matlab
Index in position 2 exceeds array bounds. Index must not exceed 1.
How to fix errors? "Index in position 2 exceeds array bounds. Index must not exceed 1".
Thanks for everyone’s help
Error in VU_MSSP_2024_QUYDAO (line 72)
Xv_2(s,i+1)=-inv(A_0(4,4))*(A_0(4,1)*Xh(s,i+1)+A_0(4,2)*Xeh(s,i+1)+A_0(4,3)*Xv_1(s,i+1)+A_0(4,5)*Xev_1(s,i+1)+A_0(4,6)*Xev_2(s,i+1)+B_0(4,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
clc
clear all;
close all;
I_1=[1];
I_2=[1 0;0 1];
Eh=[1];
Ev=[1 0;0 0];
E=blkdiag(Eh,Ev);
E_c=blkdiag(Eh,Eh,Ev,Ev);
Ih=[1];
Iv=[1 0;0 1];
J=[Ih zeros(1,5);zeros(2,2) Iv zeros(2,2);0 Ih zeros(1,4); zeros(2,2) zeros(2,2) Iv];
A=[0.04 -0.01 0.3;0.01 0.9 0.3;0.15 0.01 -0.05];
H=[-0.02 0.01 0.02;0.05 -0.01 0.05;0.47 0.01 2.02];
C=[0.05 -0.02 0.05;-0.05 0.01 0.08];
B_u=[0.01;0.02;-0.01];
B_w=[-0.02;0.05;0.04];
D_u=[0.05;0.01];
D_w=[0.02;-0.03];
A_c=blkdiag(A,A);
B_wc=[B_w;B_w];
B_c=[B_u -B_u;zeros(3,1) zeros(3,1)];
H_c=[zeros(3,3) zeros(3,3); zeros(3,3) H];
N_E=[zeros(1,6);zeros(1,6);zeros(1,6);1 1 1 1 1 1;zeros(1,6);1 1 1 -1 1 1];
D_1=[D_u -D_u];
%——————–
a=0.8;
gamma=4;
K=[ -0.4957 -9.2860 -4.8612];
L=[ -1726 -1094 43;950 603 -24;-18404 -11652 457];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A_0=J’*[A+B_u*K -B_u*K;zeros(3,3) A-L*H]*J;
B_0=J’*[B_w;B_w];
C_0=[C+D_u*K -D_u*K]*J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*exp(-0.1*(s+i))*sin(i+s);
Xv_1(s,i+1)=A_0(3,1)*Xh(s,i)+A_0(3,2)*Xeh(s,i)+A_0(3,3)*Xv_1(s,i)+A_0(3,4)*Xv_2(s,i)+A_0(3,5)*Xev_1(s,i)+A_0(3,6)*Xev_2(s,i)+B_0(3,1)*5*exp(-0.1*(s+i))*sin(i+s);
Xv_2(s,i+1)=-inv(A_0(4,4))*(A_0(4,1)*Xh(s,i+1)+A_0(4,2)*Xeh(s,i+1)+A_0(4,3)*Xv_1(s,i+1)+A_0(4,5)*Xev_1(s,i+1)+A_0(4,6)*Xev_2(s,i+1)+B_0(4,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
Xev_1(s,i+1)=A_0(5,1)*Xh(s,i)+A_0(5,2)*Xeh(s,i)+A_0(5,3)*Xv_1(s,i)+A_0(5,4)*Xv_2(s,i)+A_0(5,5)*Xev_1(s,i)+A_0(5,6)*Xev_2(s,i)+B_0(5,1)*5*exp(-0.1*(s+i))*sin(i+s);
Xev_2(s,i+1)=-inv(A_0(6,6))*(A_0(6,1)*Xh(s,i+1)+A_0(6,2)*Xeh(s,i+1)+A_0(6,3)*Xv_1(s,i+1)+A_0(6,4)*Xv_2(s,i+1)+A_0(6,5)*Xev_1(s,i+1)+B_0(6,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
Z(s,i)=norm(C_0*x0+D_w*5*exp(-0.1*(s+i))*sin(i+s));
U(s,i)=K*([Xh(s,i);Xv_1(s,i);Xv_2(s,i)]-[Xeh(s,i);Xev_1(s,i);Xev_2(s,i)]);
end
end
figure(1)
surf(v,w,Xh)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x^h(i,j)’);
%axis([0 100 0 100 -0.15 0.06])
hold on;
figure(2)
surf(v,w,Xeh)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_e^h(i,j)’);
%axis([0 100 0 100 -0.5 0.1])
hold on;
figure(3)
surf(v,w,Xv_1)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_1^v(i,j)’);
hold on;
figure(4)
surf(v,w,Xv_2)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_2^v(i,j)’);
hold on;
figure(5)
surf(v,w,Xev_1)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_{e1}^v(i,j)’);
hold on;
figure(6)
surf(v,w,Xev_2)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_{e2}^v(i,j)’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
figure(7)
surf(v,w,Z)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘||z(i,j)||’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
figure(8)
surf(v,w,U)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘u(i,j)|’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
"How to fix errors? "Index in position 2 exceeds array bounds. Index must not exceed 1".
Thanks for everyone’s help
Error in VU_MSSP_2024_QUYDAO (line 72)
Xv_2(s,i+1)=-inv(A_0(4,4))*(A_0(4,1)*Xh(s,i+1)+A_0(4,2)*Xeh(s,i+1)+A_0(4,3)*Xv_1(s,i+1)+A_0(4,5)*Xev_1(s,i+1)+A_0(4,6)*Xev_2(s,i+1)+B_0(4,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
clc
clear all;
close all;
I_1=[1];
I_2=[1 0;0 1];
Eh=[1];
Ev=[1 0;0 0];
E=blkdiag(Eh,Ev);
E_c=blkdiag(Eh,Eh,Ev,Ev);
Ih=[1];
Iv=[1 0;0 1];
J=[Ih zeros(1,5);zeros(2,2) Iv zeros(2,2);0 Ih zeros(1,4); zeros(2,2) zeros(2,2) Iv];
A=[0.04 -0.01 0.3;0.01 0.9 0.3;0.15 0.01 -0.05];
H=[-0.02 0.01 0.02;0.05 -0.01 0.05;0.47 0.01 2.02];
C=[0.05 -0.02 0.05;-0.05 0.01 0.08];
B_u=[0.01;0.02;-0.01];
B_w=[-0.02;0.05;0.04];
D_u=[0.05;0.01];
D_w=[0.02;-0.03];
A_c=blkdiag(A,A);
B_wc=[B_w;B_w];
B_c=[B_u -B_u;zeros(3,1) zeros(3,1)];
H_c=[zeros(3,3) zeros(3,3); zeros(3,3) H];
N_E=[zeros(1,6);zeros(1,6);zeros(1,6);1 1 1 1 1 1;zeros(1,6);1 1 1 -1 1 1];
D_1=[D_u -D_u];
%——————–
a=0.8;
gamma=4;
K=[ -0.4957 -9.2860 -4.8612];
L=[ -1726 -1094 43;950 603 -24;-18404 -11652 457];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A_0=J’*[A+B_u*K -B_u*K;zeros(3,3) A-L*H]*J;
B_0=J’*[B_w;B_w];
C_0=[C+D_u*K -D_u*K]*J;
n=80;
v=zeros(1,n);
w=zeros(1,n);
Xh=zeros(n,n); Xeh=zeros(n,n); Xv_1=zeros(n,n);Xv_2=zeros(n,n);Ev_1=zeros(n,n);Xev_2=zeros(n,n);Z=zeros(n,n);U=zeros(n,n);
for i=1:1:n-1
Xh(1,i)=0;
Xeh(1,i)=0;
end
for i=1:1:n-1
Xv_1(i,1)=0;
Xv_2(i,1)=0;
Xev_1(i,1)=0;
Xev_2(i,1)=0;
end
x1=zeros(6,1);x0=zeros(6,1);xc=zeros(6,1);
for i=1:1:n
v(1,i)=i;
w(1,i)=i;
end
for s=1:1:n
for i=1:1:n-1
x0(1,1)=Xh(s,i);x0(2,1)=Xeh(s,i);x0(3,1)=Xv_1(s,i);x0(4,1)=Xv_2(s,i);x0(5,1)=Xev_1(s,i);x0(6,1)=Xev_2(s,i);
x1=A_0*x0+B_0*5*exp(-0.1*(s+i))*sin(i+s);
Xh(s+1,i)=A_0(1,1)*Xh(s,i)+A_0(1,2)*Xeh(s,i)+A_0(1,3)*Xv_1(s,i)+A_0(1,4)*Xv_2(s,i)+A_0(1,5)*Xev_1(s,i)+A_0(1,6)*Xev_2(s,i)+B_0(1,1)*5*exp(-0.1*(s+i))*sin(i+s);
Xeh(s+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6,5)*Xev_1(s,i+1)+B_0(6,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
Z(s,i)=norm(C_0*x0+D_w*5*exp(-0.1*(s+i))*sin(i+s));
U(s,i)=K*([Xh(s,i);Xv_1(s,i);Xv_2(s,i)]-[Xeh(s,i);Xev_1(s,i);Xev_2(s,i)]);
end
end
figure(1)
surf(v,w,Xh)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x^h(i,j)’);
%axis([0 100 0 100 -0.15 0.06])
hold on;
figure(2)
surf(v,w,Xeh)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_e^h(i,j)’);
%axis([0 100 0 100 -0.5 0.1])
hold on;
figure(3)
surf(v,w,Xv_1)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_1^v(i,j)’);
hold on;
figure(4)
surf(v,w,Xv_2)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_2^v(i,j)’);
hold on;
figure(5)
surf(v,w,Xev_1)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_{e1}^v(i,j)’);
hold on;
figure(6)
surf(v,w,Xev_2)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_{e2}^v(i,j)’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
figure(7)
surf(v,w,Z)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘||z(i,j)||’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
figure(8)
surf(v,w,U)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘u(i,j)|’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
" How to fix errors? "Index in position 2 exceeds array bounds. Index must not exceed 1".
Thanks for everyone’s help
Error in VU_MSSP_2024_QUYDAO (line 72)
Xv_2(s,i+1)=-inv(A_0(4,4))*(A_0(4,1)*Xh(s,i+1)+A_0(4,2)*Xeh(s,i+1)+A_0(4,3)*Xv_1(s,i+1)+A_0(4,5)*Xev_1(s,i+1)+A_0(4,6)*Xev_2(s,i+1)+B_0(4,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
clc
clear all;
close all;
I_1=[1];
I_2=[1 0;0 1];
Eh=[1];
Ev=[1 0;0 0];
E=blkdiag(Eh,Ev);
E_c=blkdiag(Eh,Eh,Ev,Ev);
Ih=[1];
Iv=[1 0;0 1];
J=[Ih zeros(1,5);zeros(2,2) Iv zeros(2,2);0 Ih zeros(1,4); zeros(2,2) zeros(2,2) Iv];
A=[0.04 -0.01 0.3;0.01 0.9 0.3;0.15 0.01 -0.05];
H=[-0.02 0.01 0.02;0.05 -0.01 0.05;0.47 0.01 2.02];
C=[0.05 -0.02 0.05;-0.05 0.01 0.08];
B_u=[0.01;0.02;-0.01];
B_w=[-0.02;0.05;0.04];
D_u=[0.05;0.01];
D_w=[0.02;-0.03];
A_c=blkdiag(A,A);
B_wc=[B_w;B_w];
B_c=[B_u -B_u;zeros(3,1) zeros(3,1)];
H_c=[zeros(3,3) zeros(3,3); zeros(3,3) H];
N_E=[zeros(1,6);zeros(1,6);zeros(1,6);1 1 1 1 1 1;zeros(1,6);1 1 1 -1 1 1];
D_1=[D_u -D_u];
%——————–
a=0.8;
gamma=4;
K=[ -0.4957 -9.2860 -4.8612];
L=[ -1726 -1094 43;950 603 -24;-18404 -11652 457];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A_0=J’*[A+B_u*K -B_u*K;zeros(3,3) A-L*H]*J;
B_0=J’*[B_w;B_w];
C_0=[C+D_u*K -D_u*K]*J;
n=80;
v=zeros(1,n);
w=zeros(1,n);
Xh=zeros(n,n); Xeh=zeros(n,n); Xv_1=zeros(n,n);Xv_2=zeros(n,n);Ev_1=zeros(n,n);Xev_2=zeros(n,n);Z=zeros(n,n);U=zeros(n,n);
for i=1:1:n-1
Xh(1,i)=0;
Xeh(1,i)=0;
end
for i=1:1:n-1
Xv_1(i,1)=0;
Xv_2(i,1)=0;
Xev_1(i,1)=0;
Xev_2(i,1)=0;
end
x1=zeros(6,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,i+1)+A_0(4,3)*Xv_1(s,i+1)+A_0(4,5)*Xev_1(s,i+1)+A_0(4,6)*Xev_2(s,i+1)+B_0(4,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
Xev_1(s,i+1)=A_0(5,1)*Xh(s,i)+A_0(5,2)*Xeh(s,i)+A_0(5,3)*Xv_1(s,i)+A_0(5,4)*Xv_2(s,i)+A_0(5,5)*Xev_1(s,i)+A_0(5,6)*Xev_2(s,i)+B_0(5,1)*5*exp(-0.1*(s+i))*sin(i+s);
Xev_2(s,i+1)=-inv(A_0(6,6))*(A_0(6,1)*Xh(s,i+1)+A_0(6,2)*Xeh(s,i+1)+A_0(6,3)*Xv_1(s,i+1)+A_0(6,4)*Xv_2(s,i+1)+A_0(6,5)*Xev_1(s,i+1)+B_0(6,1)*5*exp(-0.1*(s+i+1))*sin(i+s+1));
Z(s,i)=norm(C_0*x0+D_w*5*exp(-0.1*(s+i))*sin(i+s));
U(s,i)=K*([Xh(s,i);Xv_1(s,i);Xv_2(s,i)]-[Xeh(s,i);Xev_1(s,i);Xev_2(s,i)]);
end
end
figure(1)
surf(v,w,Xh)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x^h(i,j)’);
%axis([0 100 0 100 -0.15 0.06])
hold on;
figure(2)
surf(v,w,Xeh)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_e^h(i,j)’);
%axis([0 100 0 100 -0.5 0.1])
hold on;
figure(3)
surf(v,w,Xv_1)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_1^v(i,j)’);
hold on;
figure(4)
surf(v,w,Xv_2)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_2^v(i,j)’);
hold on;
figure(5)
surf(v,w,Xev_1)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_{e1}^v(i,j)’);
hold on;
figure(6)
surf(v,w,Xev_2)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘x_{e2}^v(i,j)’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
figure(7)
surf(v,w,Z)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘||z(i,j)||’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
figure(8)
surf(v,w,U)
xlabel(‘i’);
ylabel(‘j’);
zlabel(‘u(i,j)|’);
%axis([0 100 0 100 -0.8 0.2])
hold on;
" index exceeds array bounds. MATLAB Answers — New Questions
mcb_pmsm_foc_sensorless_f28027LaunchPad
mcb_pmsm_foc_sensorless_f28027LaunchPad Why is the default pi of the model so significant? I directly used the pi parameters set by the hardware, burned them directly, and found that the speed fluctuation was large through PMSM FOC Host control. Do you have a detailed introduction to this model? Just startedmcb_pmsm_foc_sensorless_f28027LaunchPad Why is the default pi of the model so significant? I directly used the pi parameters set by the hardware, burned them directly, and found that the speed fluctuation was large through PMSM FOC Host control. Do you have a detailed introduction to this model? Just started mcb_pmsm_foc_sensorless_f28027LaunchPad Why is the default pi of the model so significant? I directly used the pi parameters set by the hardware, burned them directly, and found that the speed fluctuation was large through PMSM FOC Host control. Do you have a detailed introduction to this model? Just started pi c2000 MATLAB Answers — New Questions
In Diagnostic Feature Designer, how can I change the color for each signal in plot?
I encountered a weird problem when trying the example in
Analyze and Select Features for Pump Diagnostics – MATLAB & Simulink (mathworks.com)
In this manual, each signal is plot using a quite distinct color, like the examples below:
However, in my MATLAB, what I got is like below, that is all signals use very similar colors:
I there anybody knows what is wrong here?
Or, how to set the colormap or color each signal using distinct colors in Diagnostic Feature Designer?I encountered a weird problem when trying the example in
Analyze and Select Features for Pump Diagnostics – MATLAB & Simulink (mathworks.com)
In this manual, each signal is plot using a quite distinct color, like the examples below:
However, in my MATLAB, what I got is like below, that is all signals use very similar colors:
I there anybody knows what is wrong here?
Or, how to set the colormap or color each signal using distinct colors in Diagnostic Feature Designer? I encountered a weird problem when trying the example in
Analyze and Select Features for Pump Diagnostics – MATLAB & Simulink (mathworks.com)
In this manual, each signal is plot using a quite distinct color, like the examples below:
However, in my MATLAB, what I got is like below, that is all signals use very similar colors:
I there anybody knows what is wrong here?
Or, how to set the colormap or color each signal using distinct colors in Diagnostic Feature Designer? diagnostic feature designer, colormap MATLAB Answers — New Questions
Trying to use an S- Function to run an LCD display with an I2C interface on Ardiuno
I have been trying to interface my Arduino Mega2560 with a 20×4 LCD display. I need to connect it to other systems in Simulink so I read on a different forum one of the best ways to do this was through an S function block. I used the I2C LCD library from https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library to run my function on the Arduino IDE, so I am pretty sure the function is not the problem. One of the issues I cannot seem to solve is that the library for the I2C requires the Wire.h library and I have been unable to find a download for this.
The function in C++ I am trying to call in the S function is:
#include "DispFCN.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
char unit_string[10];
char Disp_string[50];
LiquidCrystal_I2C lcd(0x27, 20, 4);
void DispFCN(int dataWhole, int dataDeci, int unit_ID) {
// The First step is to identify the type of unit by its ID
if (unit_ID == 1) {
sprintf(unit_string, "m/s");
} // This ID denotes windspeed
else if (unit_ID == 2) {
sprintf(unit_string, "F");
} // This ID denotes Temperature in F
sprintf(Disp_string, "%d.%d %s", A, B, unit_string);
// Print a message to the LCD.
lcd.backlight();
lcd.setCursor(1, 0);
lcd.print("Wind Velocity:");
lcd.setCursor(1, 1);
lcd.print(Disp_string);
}
Below is the way that I setup the S function:
The procedure that I was following to build the S function is based off of what was recommended in: https://www.youtube.com/watch?v=L86n9wZZz-g
I have a number of thoughts as to why it is not working, but the error from Simulink seems to imply that I need a version of Wire.h for the I2C LCD library to work, but I cannot find a copy of the Wire.h file to give to Matlab, so I am not sure what I need to do to get the S function to work.I have been trying to interface my Arduino Mega2560 with a 20×4 LCD display. I need to connect it to other systems in Simulink so I read on a different forum one of the best ways to do this was through an S function block. I used the I2C LCD library from https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library to run my function on the Arduino IDE, so I am pretty sure the function is not the problem. One of the issues I cannot seem to solve is that the library for the I2C requires the Wire.h library and I have been unable to find a download for this.
The function in C++ I am trying to call in the S function is:
#include "DispFCN.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
char unit_string[10];
char Disp_string[50];
LiquidCrystal_I2C lcd(0x27, 20, 4);
void DispFCN(int dataWhole, int dataDeci, int unit_ID) {
// The First step is to identify the type of unit by its ID
if (unit_ID == 1) {
sprintf(unit_string, "m/s");
} // This ID denotes windspeed
else if (unit_ID == 2) {
sprintf(unit_string, "F");
} // This ID denotes Temperature in F
sprintf(Disp_string, "%d.%d %s", A, B, unit_string);
// Print a message to the LCD.
lcd.backlight();
lcd.setCursor(1, 0);
lcd.print("Wind Velocity:");
lcd.setCursor(1, 1);
lcd.print(Disp_string);
}
Below is the way that I setup the S function:
The procedure that I was following to build the S function is based off of what was recommended in: https://www.youtube.com/watch?v=L86n9wZZz-g
I have a number of thoughts as to why it is not working, but the error from Simulink seems to imply that I need a version of Wire.h for the I2C LCD library to work, but I cannot find a copy of the Wire.h file to give to Matlab, so I am not sure what I need to do to get the S function to work. I have been trying to interface my Arduino Mega2560 with a 20×4 LCD display. I need to connect it to other systems in Simulink so I read on a different forum one of the best ways to do this was through an S function block. I used the I2C LCD library from https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library to run my function on the Arduino IDE, so I am pretty sure the function is not the problem. One of the issues I cannot seem to solve is that the library for the I2C requires the Wire.h library and I have been unable to find a download for this.
The function in C++ I am trying to call in the S function is:
#include "DispFCN.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
char unit_string[10];
char Disp_string[50];
LiquidCrystal_I2C lcd(0x27, 20, 4);
void DispFCN(int dataWhole, int dataDeci, int unit_ID) {
// The First step is to identify the type of unit by its ID
if (unit_ID == 1) {
sprintf(unit_string, "m/s");
} // This ID denotes windspeed
else if (unit_ID == 2) {
sprintf(unit_string, "F");
} // This ID denotes Temperature in F
sprintf(Disp_string, "%d.%d %s", A, B, unit_string);
// Print a message to the LCD.
lcd.backlight();
lcd.setCursor(1, 0);
lcd.print("Wind Velocity:");
lcd.setCursor(1, 1);
lcd.print(Disp_string);
}
Below is the way that I setup the S function:
The procedure that I was following to build the S function is based off of what was recommended in: https://www.youtube.com/watch?v=L86n9wZZz-g
I have a number of thoughts as to why it is not working, but the error from Simulink seems to imply that I need a version of Wire.h for the I2C LCD library to work, but I cannot find a copy of the Wire.h file to give to Matlab, so I am not sure what I need to do to get the S function to work. sfunctions, simulink, matlab, lcd, i2c, iic MATLAB Answers — New Questions
Image Denoising of SEM Image
Hello,
I am trying to analyse microstructural features in one of my image. Yet I have couple of problems on the image. First of all, one of my friends has denoised the image using python and he did not share the details of denosising. When I try to denoise image by myself, I cannot get close to his denosising so I am wodering what I should do and what he used for denoising so that he got such a clear image. I have added the image before and after denosising (hope you can see the zip file).
Also another question is that I was using the thresholded image to measure microstructural features like length, width and volume fraction of yellow and chunky purple ones via imageJ and python. I am wondering if I can do the same with Matlab in a better way. I know my thresholding could be better but with limited coding skills that is what I can do currently 🙂 So next question is how I can do a better thresholding to distinguish each phases which are gray, white and black in the original image
Thank you in advance.Hello,
I am trying to analyse microstructural features in one of my image. Yet I have couple of problems on the image. First of all, one of my friends has denoised the image using python and he did not share the details of denosising. When I try to denoise image by myself, I cannot get close to his denosising so I am wodering what I should do and what he used for denoising so that he got such a clear image. I have added the image before and after denosising (hope you can see the zip file).
Also another question is that I was using the thresholded image to measure microstructural features like length, width and volume fraction of yellow and chunky purple ones via imageJ and python. I am wondering if I can do the same with Matlab in a better way. I know my thresholding could be better but with limited coding skills that is what I can do currently 🙂 So next question is how I can do a better thresholding to distinguish each phases which are gray, white and black in the original image
Thank you in advance. Hello,
I am trying to analyse microstructural features in one of my image. Yet I have couple of problems on the image. First of all, one of my friends has denoised the image using python and he did not share the details of denosising. When I try to denoise image by myself, I cannot get close to his denosising so I am wodering what I should do and what he used for denoising so that he got such a clear image. I have added the image before and after denosising (hope you can see the zip file).
Also another question is that I was using the thresholded image to measure microstructural features like length, width and volume fraction of yellow and chunky purple ones via imageJ and python. I am wondering if I can do the same with Matlab in a better way. I know my thresholding could be better but with limited coding skills that is what I can do currently 🙂 So next question is how I can do a better thresholding to distinguish each phases which are gray, white and black in the original image
Thank you in advance. image analysis, image processing MATLAB Answers — New Questions
How do I fix/find this error when using OSPREY?
I’m trying to us OSPREY to process MRS data, I get through the steps "load data" and "process data" but I keep getting this error when I try to move on to "model data" step.
Reference to non-existent field ‘np_sw_2048_2999.4001’.
Error in osp_plotModule (line 426)
basisSet = MRSCont.fit.resBasisSet.(which).([‘np_sw_’ num2str(MRSCont.processed.metab{kk}.sz(1)) ‘_’
num2str(MRSCont.processed.metab{kk}.spectralwidth)]){basis,1,subspectrum};
Error in osp_plotAllPDF (line 76)
osp_plotModule(MRSCont, ‘OspreyFit’, kk,[bb ss], Names{mm});
Error in OspreyFit (line 235)
osp_plotAllPDF(MRSCont, ‘OspreyFit’);
Error in osp_onFit (line 35)
MRSCont = OspreyFit(MRSCont);
Error while evaluating UIControl Callback.I’m trying to us OSPREY to process MRS data, I get through the steps "load data" and "process data" but I keep getting this error when I try to move on to "model data" step.
Reference to non-existent field ‘np_sw_2048_2999.4001’.
Error in osp_plotModule (line 426)
basisSet = MRSCont.fit.resBasisSet.(which).([‘np_sw_’ num2str(MRSCont.processed.metab{kk}.sz(1)) ‘_’
num2str(MRSCont.processed.metab{kk}.spectralwidth)]){basis,1,subspectrum};
Error in osp_plotAllPDF (line 76)
osp_plotModule(MRSCont, ‘OspreyFit’, kk,[bb ss], Names{mm});
Error in OspreyFit (line 235)
osp_plotAllPDF(MRSCont, ‘OspreyFit’);
Error in osp_onFit (line 35)
MRSCont = OspreyFit(MRSCont);
Error while evaluating UIControl Callback. I’m trying to us OSPREY to process MRS data, I get through the steps "load data" and "process data" but I keep getting this error when I try to move on to "model data" step.
Reference to non-existent field ‘np_sw_2048_2999.4001’.
Error in osp_plotModule (line 426)
basisSet = MRSCont.fit.resBasisSet.(which).([‘np_sw_’ num2str(MRSCont.processed.metab{kk}.sz(1)) ‘_’
num2str(MRSCont.processed.metab{kk}.spectralwidth)]){basis,1,subspectrum};
Error in osp_plotAllPDF (line 76)
osp_plotModule(MRSCont, ‘OspreyFit’, kk,[bb ss], Names{mm});
Error in OspreyFit (line 235)
osp_plotAllPDF(MRSCont, ‘OspreyFit’);
Error in osp_onFit (line 35)
MRSCont = OspreyFit(MRSCont);
Error while evaluating UIControl Callback. osprey, mrs, matlab MATLAB Answers — New Questions
How to deselect a cell on uitable using CellSelectionCallback?
Hi,
Tried several solutions found in the forum but none of them worked,
in my program, when a cell is selected, all the info of the row is displayed in different edit cases, when the cell in the uitable is edited and enter is pressed, the wanted value changes properly but the CellSelectionCallback is called again and the indices this time are inexistent and returns an error.
Any way of fixing this?
Thanks in advanceHi,
Tried several solutions found in the forum but none of them worked,
in my program, when a cell is selected, all the info of the row is displayed in different edit cases, when the cell in the uitable is edited and enter is pressed, the wanted value changes properly but the CellSelectionCallback is called again and the indices this time are inexistent and returns an error.
Any way of fixing this?
Thanks in advance Hi,
Tried several solutions found in the forum but none of them worked,
in my program, when a cell is selected, all the info of the row is displayed in different edit cases, when the cell in the uitable is edited and enter is pressed, the wanted value changes properly but the CellSelectionCallback is called again and the indices this time are inexistent and returns an error.
Any way of fixing this?
Thanks in advance deselect MATLAB Answers — New Questions
How to delete default excel sheets when using writetable function (mac)?
When using the writetable function to add several different sheets, excel generates default (blank) excel sheets at the beginning of the document. I currently am working off a mac computer and thus cannot use the actxserver solutions described in other posts.
writetable(T,filename,’sheet’,’sheet_name’);When using the writetable function to add several different sheets, excel generates default (blank) excel sheets at the beginning of the document. I currently am working off a mac computer and thus cannot use the actxserver solutions described in other posts.
writetable(T,filename,’sheet’,’sheet_name’); When using the writetable function to add several different sheets, excel generates default (blank) excel sheets at the beginning of the document. I currently am working off a mac computer and thus cannot use the actxserver solutions described in other posts.
writetable(T,filename,’sheet’,’sheet_name’); writetable, excel, sheets MATLAB Answers — New Questions
Modifying Loss Function for Deep Reinforcement Learning Agent
Hi.
Im Looking to use the DQN agent for some initial study of a problem that Im working on. The problem requires that I modify the loss function used in training of the Q-approximation network in DQN. I have the equation that I need to use to modify the loss function, it will be an additional term added to the standard loss function, which is squares sum of target and predicted Q network values. The new term will be like sum of squares of predicted and some expert Q value.
I would like to know if its possible to just modify the loss function, add the new term, and still use the framework presented by Reinforcement Learning Toolbox? Or this is not possible and I would have to atleast write all the code for DQN agents learning part?
Thanks for your time and help!Hi.
Im Looking to use the DQN agent for some initial study of a problem that Im working on. The problem requires that I modify the loss function used in training of the Q-approximation network in DQN. I have the equation that I need to use to modify the loss function, it will be an additional term added to the standard loss function, which is squares sum of target and predicted Q network values. The new term will be like sum of squares of predicted and some expert Q value.
I would like to know if its possible to just modify the loss function, add the new term, and still use the framework presented by Reinforcement Learning Toolbox? Or this is not possible and I would have to atleast write all the code for DQN agents learning part?
Thanks for your time and help! Hi.
Im Looking to use the DQN agent for some initial study of a problem that Im working on. The problem requires that I modify the loss function used in training of the Q-approximation network in DQN. I have the equation that I need to use to modify the loss function, it will be an additional term added to the standard loss function, which is squares sum of target and predicted Q network values. The new term will be like sum of squares of predicted and some expert Q value.
I would like to know if its possible to just modify the loss function, add the new term, and still use the framework presented by Reinforcement Learning Toolbox? Or this is not possible and I would have to atleast write all the code for DQN agents learning part?
Thanks for your time and help! reinforcement learning, loss function, dqn MATLAB Answers — New Questions
how to find the element which is greater than or equal to its row and smaller or equal to its column in a matrix
Hi everyone;
I am going to find the saddle points of a matrix M. The question is given below…
Write a function called saddle that finds saddle points in the input matrix M. For the purposes of this problem, a saddle point is defined as an element whose value is greater than or equal to every element in its row, and less than or equal to every element in its column. Note that there may be more than one saddle point in M. Return a matrix indices that has exactly two columns. Each row of indices corresponds to one saddle point with the first element of the row containing the row index of the saddle point and the second column containing the column index. The saddle points are provided in indices in the same order they are located in M according to column-major ordering. If there is no saddle point in M, then indices is the empty array.
I am trying that code:
function indices = saddle(M)
[ rows,cols ] = size(M);
[valR,posR] = max(M,[],2);
[valC,posC] = min(M,[],1);
indices= [];
for i = 1:length(posR)
if i == posC(posR(i))
indices= [indices; i, posR(i)];
end
end
end
It is running fine. But when i test my code for
>> mat=zeros(5,3)
mat =
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
I am getting wrong output :
saddle(mat)
ans =
1 1
the correct output must be
saddle(mat)
ans =
1 1
2 1
3 1
4 1
5 1
1 2
2 2
3 2
4 2
5 2
1 3
2 3
3 3
4 3
5 3
What i am doing wrong?? Thanks in advanceHi everyone;
I am going to find the saddle points of a matrix M. The question is given below…
Write a function called saddle that finds saddle points in the input matrix M. For the purposes of this problem, a saddle point is defined as an element whose value is greater than or equal to every element in its row, and less than or equal to every element in its column. Note that there may be more than one saddle point in M. Return a matrix indices that has exactly two columns. Each row of indices corresponds to one saddle point with the first element of the row containing the row index of the saddle point and the second column containing the column index. The saddle points are provided in indices in the same order they are located in M according to column-major ordering. If there is no saddle point in M, then indices is the empty array.
I am trying that code:
function indices = saddle(M)
[ rows,cols ] = size(M);
[valR,posR] = max(M,[],2);
[valC,posC] = min(M,[],1);
indices= [];
for i = 1:length(posR)
if i == posC(posR(i))
indices= [indices; i, posR(i)];
end
end
end
It is running fine. But when i test my code for
>> mat=zeros(5,3)
mat =
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
I am getting wrong output :
saddle(mat)
ans =
1 1
the correct output must be
saddle(mat)
ans =
1 1
2 1
3 1
4 1
5 1
1 2
2 2
3 2
4 2
5 2
1 3
2 3
3 3
4 3
5 3
What i am doing wrong?? Thanks in advance Hi everyone;
I am going to find the saddle points of a matrix M. The question is given below…
Write a function called saddle that finds saddle points in the input matrix M. For the purposes of this problem, a saddle point is defined as an element whose value is greater than or equal to every element in its row, and less than or equal to every element in its column. Note that there may be more than one saddle point in M. Return a matrix indices that has exactly two columns. Each row of indices corresponds to one saddle point with the first element of the row containing the row index of the saddle point and the second column containing the column index. The saddle points are provided in indices in the same order they are located in M according to column-major ordering. If there is no saddle point in M, then indices is the empty array.
I am trying that code:
function indices = saddle(M)
[ rows,cols ] = size(M);
[valR,posR] = max(M,[],2);
[valC,posC] = min(M,[],1);
indices= [];
for i = 1:length(posR)
if i == posC(posR(i))
indices= [indices; i, posR(i)];
end
end
end
It is running fine. But when i test my code for
>> mat=zeros(5,3)
mat =
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
I am getting wrong output :
saddle(mat)
ans =
1 1
the correct output must be
saddle(mat)
ans =
1 1
2 1
3 1
4 1
5 1
1 2
2 2
3 2
4 2
5 2
1 3
2 3
3 3
4 3
5 3
What i am doing wrong?? Thanks in advance order, matrix, homework MATLAB Answers — New Questions
inverse kinematics (self made function) errors
% This is my current code. I am attempting to use inverse kinematics to
% plot the same semicircle i made using forward kinematics. My issue is
% that the function i am currently using doesn’t properly calculate the
% "joint2" angle (it prints the same value always)
% NOTE: the error i am having occurs mostly in STEP 4 of my code.
clear;
clc;
% Step one: Defining linked robot and confirming it is correct
L_1(1) = Link([0 199.07 0 pi/2]);
L_1(2) = Link([0 -27 -23.33 -pi/2]);
L_1(3) = Link([0 -12.18 0 0]);
L_1(4) = Link([0 0 0 -pi/2]);
L_1(5) = Link([0 0 107.92 0]);
L_1(6) = Link([0 0 0 0]);
L_1(7) = Link([0 0 133.99 0]);
robot1 = SerialLink(L_1);
figure(2);
robot1.plot([pi/2 0 pi/2 0 0.6542 1.36 0], ‘nojoints’);
hold on;
% Success
% ——————————————————————— %
% Step two: retrieving end effector coordinates and confirming thier
% position
coor = robot1.fkine([pi/2 0 pi/2 0 0.6542 1.36 0]);
xF = coor.t(1);
yF = coor.t(2);
zF = coor.t(3);
% disp([‘(‘, num2str(xF), ‘ , ‘, num2str(yF) , ‘ , ‘ num2str(zF), ‘)’]);
% plot3(xF,yF,zF, ‘o’, ‘Color’, ‘g’);
% Success
% ——————————————————————— %
% Step three: plotting a semicircle
radius_S3 = 200;
pointsNum = ( pi/(pi/16) + 1);
semiCircleArray = zeros(pointsNum, 3);
index = 1;
for theta = pi : -pi/16 : 0
xF = radius_S3 * cos(theta);
yF = -23.33;
zF = radius_S3 * sin(theta);
plot3(xF,yF,zF, ‘*’, ‘Color’, ‘r’);
% disp([‘(‘, num2str(xForward), ‘ , ‘, num2str(yForward) , ‘ , ‘ num2str(zForward), ‘)’]);
semiCircleArray(index, 🙂 = [xF, yF, zF];
index = index + 1;
end
plot3(semiCircleArray(:, 1), semiCircleArray(:, 2), semiCircleArray(:, 3), ‘o’, ‘Color’, ‘b’);
% Success
% ——————————————————————— %
% Step four: inserting array values into function to confirm angles.
joint1 = zeros(pointsNum, 1);
joint2 = zeros(pointsNum, 1);
for i = 1:pointsNum
[joint1(i), joint2(i)] = theta2Output(semiCircleArray(i, 3), semiCircleArray(i, 1));
disp([‘j1: ‘, num2str(joint1(i)), ‘ , j2: ‘, num2str(joint2(i))]);
end
% This is where something goes wrong, which confirms there is an issue
% with my function. The value of one joint angle slowly increments
% whilst the other stays unchanged.
title(‘Right Leg – J1 J2 J3’);
xlabel(‘x-axis’);
ylabel(‘y-axis’);
zlabel(‘z-axis’);
function [joint1 , joint2] = theta2Output(x, z)
l1 = 107.92;
l2 = 133.99;
x = x(:);
z = z(:);
term1 = x.^2;
term2 = z.^2;
term3 = l1^2;
term4 = l2^2;
cos_joint2 = (term1 + term2 – term3 – term4) / (2 * l2 * l1);
joint2 = acos(cos_joint2);
joint1 = atan2(x , z) – atan2((l2 * sin(joint2)) , (l1 + (l2*cos(joint2))));
end% This is my current code. I am attempting to use inverse kinematics to
% plot the same semicircle i made using forward kinematics. My issue is
% that the function i am currently using doesn’t properly calculate the
% "joint2" angle (it prints the same value always)
% NOTE: the error i am having occurs mostly in STEP 4 of my code.
clear;
clc;
% Step one: Defining linked robot and confirming it is correct
L_1(1) = Link([0 199.07 0 pi/2]);
L_1(2) = Link([0 -27 -23.33 -pi/2]);
L_1(3) = Link([0 -12.18 0 0]);
L_1(4) = Link([0 0 0 -pi/2]);
L_1(5) = Link([0 0 107.92 0]);
L_1(6) = Link([0 0 0 0]);
L_1(7) = Link([0 0 133.99 0]);
robot1 = SerialLink(L_1);
figure(2);
robot1.plot([pi/2 0 pi/2 0 0.6542 1.36 0], ‘nojoints’);
hold on;
% Success
% ——————————————————————— %
% Step two: retrieving end effector coordinates and confirming thier
% position
coor = robot1.fkine([pi/2 0 pi/2 0 0.6542 1.36 0]);
xF = coor.t(1);
yF = coor.t(2);
zF = coor.t(3);
% disp([‘(‘, num2str(xF), ‘ , ‘, num2str(yF) , ‘ , ‘ num2str(zF), ‘)’]);
% plot3(xF,yF,zF, ‘o’, ‘Color’, ‘g’);
% Success
% ——————————————————————— %
% Step three: plotting a semicircle
radius_S3 = 200;
pointsNum = ( pi/(pi/16) + 1);
semiCircleArray = zeros(pointsNum, 3);
index = 1;
for theta = pi : -pi/16 : 0
xF = radius_S3 * cos(theta);
yF = -23.33;
zF = radius_S3 * sin(theta);
plot3(xF,yF,zF, ‘*’, ‘Color’, ‘r’);
% disp([‘(‘, num2str(xForward), ‘ , ‘, num2str(yForward) , ‘ , ‘ num2str(zForward), ‘)’]);
semiCircleArray(index, 🙂 = [xF, yF, zF];
index = index + 1;
end
plot3(semiCircleArray(:, 1), semiCircleArray(:, 2), semiCircleArray(:, 3), ‘o’, ‘Color’, ‘b’);
% Success
% ——————————————————————— %
% Step four: inserting array values into function to confirm angles.
joint1 = zeros(pointsNum, 1);
joint2 = zeros(pointsNum, 1);
for i = 1:pointsNum
[joint1(i), joint2(i)] = theta2Output(semiCircleArray(i, 3), semiCircleArray(i, 1));
disp([‘j1: ‘, num2str(joint1(i)), ‘ , j2: ‘, num2str(joint2(i))]);
end
% This is where something goes wrong, which confirms there is an issue
% with my function. The value of one joint angle slowly increments
% whilst the other stays unchanged.
title(‘Right Leg – J1 J2 J3’);
xlabel(‘x-axis’);
ylabel(‘y-axis’);
zlabel(‘z-axis’);
function [joint1 , joint2] = theta2Output(x, z)
l1 = 107.92;
l2 = 133.99;
x = x(:);
z = z(:);
term1 = x.^2;
term2 = z.^2;
term3 = l1^2;
term4 = l2^2;
cos_joint2 = (term1 + term2 – term3 – term4) / (2 * l2 * l1);
joint2 = acos(cos_joint2);
joint1 = atan2(x , z) – atan2((l2 * sin(joint2)) , (l1 + (l2*cos(joint2))));
end % This is my current code. I am attempting to use inverse kinematics to
% plot the same semicircle i made using forward kinematics. My issue is
% that the function i am currently using doesn’t properly calculate the
% "joint2" angle (it prints the same value always)
% NOTE: the error i am having occurs mostly in STEP 4 of my code.
clear;
clc;
% Step one: Defining linked robot and confirming it is correct
L_1(1) = Link([0 199.07 0 pi/2]);
L_1(2) = Link([0 -27 -23.33 -pi/2]);
L_1(3) = Link([0 -12.18 0 0]);
L_1(4) = Link([0 0 0 -pi/2]);
L_1(5) = Link([0 0 107.92 0]);
L_1(6) = Link([0 0 0 0]);
L_1(7) = Link([0 0 133.99 0]);
robot1 = SerialLink(L_1);
figure(2);
robot1.plot([pi/2 0 pi/2 0 0.6542 1.36 0], ‘nojoints’);
hold on;
% Success
% ——————————————————————— %
% Step two: retrieving end effector coordinates and confirming thier
% position
coor = robot1.fkine([pi/2 0 pi/2 0 0.6542 1.36 0]);
xF = coor.t(1);
yF = coor.t(2);
zF = coor.t(3);
% disp([‘(‘, num2str(xF), ‘ , ‘, num2str(yF) , ‘ , ‘ num2str(zF), ‘)’]);
% plot3(xF,yF,zF, ‘o’, ‘Color’, ‘g’);
% Success
% ——————————————————————— %
% Step three: plotting a semicircle
radius_S3 = 200;
pointsNum = ( pi/(pi/16) + 1);
semiCircleArray = zeros(pointsNum, 3);
index = 1;
for theta = pi : -pi/16 : 0
xF = radius_S3 * cos(theta);
yF = -23.33;
zF = radius_S3 * sin(theta);
plot3(xF,yF,zF, ‘*’, ‘Color’, ‘r’);
% disp([‘(‘, num2str(xForward), ‘ , ‘, num2str(yForward) , ‘ , ‘ num2str(zForward), ‘)’]);
semiCircleArray(index, 🙂 = [xF, yF, zF];
index = index + 1;
end
plot3(semiCircleArray(:, 1), semiCircleArray(:, 2), semiCircleArray(:, 3), ‘o’, ‘Color’, ‘b’);
% Success
% ——————————————————————— %
% Step four: inserting array values into function to confirm angles.
joint1 = zeros(pointsNum, 1);
joint2 = zeros(pointsNum, 1);
for i = 1:pointsNum
[joint1(i), joint2(i)] = theta2Output(semiCircleArray(i, 3), semiCircleArray(i, 1));
disp([‘j1: ‘, num2str(joint1(i)), ‘ , j2: ‘, num2str(joint2(i))]);
end
% This is where something goes wrong, which confirms there is an issue
% with my function. The value of one joint angle slowly increments
% whilst the other stays unchanged.
title(‘Right Leg – J1 J2 J3’);
xlabel(‘x-axis’);
ylabel(‘y-axis’);
zlabel(‘z-axis’);
function [joint1 , joint2] = theta2Output(x, z)
l1 = 107.92;
l2 = 133.99;
x = x(:);
z = z(:);
term1 = x.^2;
term2 = z.^2;
term3 = l1^2;
term4 = l2^2;
cos_joint2 = (term1 + term2 – term3 – term4) / (2 * l2 * l1);
joint2 = acos(cos_joint2);
joint1 = atan2(x , z) – atan2((l2 * sin(joint2)) , (l1 + (l2*cos(joint2))));
end inverse kinematics, serial robot MATLAB Answers — New Questions
Is there a simulink version that works with Inventor 2022 and later?
The simulink description page said that the inventor is only supported up to the 2021 version.
Currently, with the 2025 version coming out, it is not possible to download the 2021 version.
Is there a simulink version that is compatible with 2022 or later versions of the inventor?The simulink description page said that the inventor is only supported up to the 2021 version.
Currently, with the 2025 version coming out, it is not possible to download the 2021 version.
Is there a simulink version that is compatible with 2022 or later versions of the inventor? The simulink description page said that the inventor is only supported up to the 2021 version.
Currently, with the 2025 version coming out, it is not possible to download the 2021 version.
Is there a simulink version that is compatible with 2022 or later versions of the inventor? simulink, inventor, compatible MATLAB Answers — New Questions
MathWorks Service Host is drastically slowing down starttime and fills up users $HOME
We have the same issue as https://www.mathworks.com/matlabcentral/answers/2128851-why-is-the-mathworks-service-host-causing-issues-with-my-cluster-and-or-hpc and I see there that "For R2024a and newer, regardless of your licensing, the MathWorks Service Host is required"
When running in a cluster, this process is repeated every time MATLAB is started on a new node.
This not only causes uneccessary delays but it also piles up lots of data on the users’ HOME space.
If we have 300 nodes, at ~640MB per node under $HOME/.MathWorks/ServiceHost a user would require more than 180GB just to host this data. This makes version 2024 not suitable for cluster environments.
How do we fix this issue?We have the same issue as https://www.mathworks.com/matlabcentral/answers/2128851-why-is-the-mathworks-service-host-causing-issues-with-my-cluster-and-or-hpc and I see there that "For R2024a and newer, regardless of your licensing, the MathWorks Service Host is required"
When running in a cluster, this process is repeated every time MATLAB is started on a new node.
This not only causes uneccessary delays but it also piles up lots of data on the users’ HOME space.
If we have 300 nodes, at ~640MB per node under $HOME/.MathWorks/ServiceHost a user would require more than 180GB just to host this data. This makes version 2024 not suitable for cluster environments.
How do we fix this issue? We have the same issue as https://www.mathworks.com/matlabcentral/answers/2128851-why-is-the-mathworks-service-host-causing-issues-with-my-cluster-and-or-hpc and I see there that "For R2024a and newer, regardless of your licensing, the MathWorks Service Host is required"
When running in a cluster, this process is repeated every time MATLAB is started on a new node.
This not only causes uneccessary delays but it also piles up lots of data on the users’ HOME space.
If we have 300 nodes, at ~640MB per node under $HOME/.MathWorks/ServiceHost a user would require more than 180GB just to host this data. This makes version 2024 not suitable for cluster environments.
How do we fix this issue? mathworks service host cluster hpc MATLAB Answers — New Questions
agent doesn’t take different actions to different states
Hello everyone,
I have two issues:
I wasn’t able to set up the environment so that the agent takes 24 different actions over the course of a day, meaning the agent takes one action every hour. As a workaround, I decided to train agents by the hour.
The second issue, which is the reason for my question, arises after training the agent. When I test the efficiency of its decision-making and run the simulation part of the RL Toolbox, I notice that the agent always takes the same action regardless of the state of the environment. This leads me to believe that the training process determines the best action for a set of states, which is not what I want. I want the agent to take the correct action for different states. I’ve been analyzing my environment code but can’t figure out why the agent behaves this way.
Thank you in advance.
BryanHello everyone,
I have two issues:
I wasn’t able to set up the environment so that the agent takes 24 different actions over the course of a day, meaning the agent takes one action every hour. As a workaround, I decided to train agents by the hour.
The second issue, which is the reason for my question, arises after training the agent. When I test the efficiency of its decision-making and run the simulation part of the RL Toolbox, I notice that the agent always takes the same action regardless of the state of the environment. This leads me to believe that the training process determines the best action for a set of states, which is not what I want. I want the agent to take the correct action for different states. I’ve been analyzing my environment code but can’t figure out why the agent behaves this way.
Thank you in advance.
Bryan Hello everyone,
I have two issues:
I wasn’t able to set up the environment so that the agent takes 24 different actions over the course of a day, meaning the agent takes one action every hour. As a workaround, I decided to train agents by the hour.
The second issue, which is the reason for my question, arises after training the agent. When I test the efficiency of its decision-making and run the simulation part of the RL Toolbox, I notice that the agent always takes the same action regardless of the state of the environment. This leads me to believe that the training process determines the best action for a set of states, which is not what I want. I want the agent to take the correct action for different states. I’ve been analyzing my environment code but can’t figure out why the agent behaves this way.
Thank you in advance.
Bryan agent drl, action agent, rl toobox MATLAB Answers — New Questions
How do I debug DLL code in Visual Studio after using loadlibrary in MATLAB?
I have a C++ code that I have compiled in Visual Studio 2022 as a DLL. I use MATLAB to call the DLL using the function loadlibrary. The code executes no problem. However, I want to enter the Visual Studio debugger to step through the code once MATLAB calls the DLL. Years ago in a previous version of Visual Studio and MATLAB, a friend showed me how to connect Visual Studio to MATLAB. In Visual Studio, I would select "Build->Attach to process" and pick the MATLAB process that would appear in the window. Then, I could add a breakpoint in the C code, and when MATLAB called the DLL, the Visual Studio debugger would stop code execution at the break point and let me step through the code. I’m unable to do that now for some reason. When I attach MATLAB to Visual Studio, the breakpoint turns to an empty red outline circle with a caution triangle on it. When I hover over it, the tooltip says "The breakpoint will not currently be hit. No symbols have been loaded for this document." The Symbol Status column of the Debug->Windows->Modules dialog says "Cannot find or open the PDB file." I’m unsure what to do here. I’m sure I’m just forgetting a step that I was shown years back. Any help would be appreciated. Note Visual Studio did create a pdb file along with the DLL and both are in the same directory. Also, I compiled in debug mode, not release mode.I have a C++ code that I have compiled in Visual Studio 2022 as a DLL. I use MATLAB to call the DLL using the function loadlibrary. The code executes no problem. However, I want to enter the Visual Studio debugger to step through the code once MATLAB calls the DLL. Years ago in a previous version of Visual Studio and MATLAB, a friend showed me how to connect Visual Studio to MATLAB. In Visual Studio, I would select "Build->Attach to process" and pick the MATLAB process that would appear in the window. Then, I could add a breakpoint in the C code, and when MATLAB called the DLL, the Visual Studio debugger would stop code execution at the break point and let me step through the code. I’m unable to do that now for some reason. When I attach MATLAB to Visual Studio, the breakpoint turns to an empty red outline circle with a caution triangle on it. When I hover over it, the tooltip says "The breakpoint will not currently be hit. No symbols have been loaded for this document." The Symbol Status column of the Debug->Windows->Modules dialog says "Cannot find or open the PDB file." I’m unsure what to do here. I’m sure I’m just forgetting a step that I was shown years back. Any help would be appreciated. Note Visual Studio did create a pdb file along with the DLL and both are in the same directory. Also, I compiled in debug mode, not release mode. I have a C++ code that I have compiled in Visual Studio 2022 as a DLL. I use MATLAB to call the DLL using the function loadlibrary. The code executes no problem. However, I want to enter the Visual Studio debugger to step through the code once MATLAB calls the DLL. Years ago in a previous version of Visual Studio and MATLAB, a friend showed me how to connect Visual Studio to MATLAB. In Visual Studio, I would select "Build->Attach to process" and pick the MATLAB process that would appear in the window. Then, I could add a breakpoint in the C code, and when MATLAB called the DLL, the Visual Studio debugger would stop code execution at the break point and let me step through the code. I’m unable to do that now for some reason. When I attach MATLAB to Visual Studio, the breakpoint turns to an empty red outline circle with a caution triangle on it. When I hover over it, the tooltip says "The breakpoint will not currently be hit. No symbols have been loaded for this document." The Symbol Status column of the Debug->Windows->Modules dialog says "Cannot find or open the PDB file." I’m unsure what to do here. I’m sure I’m just forgetting a step that I was shown years back. Any help would be appreciated. Note Visual Studio did create a pdb file along with the DLL and both are in the same directory. Also, I compiled in debug mode, not release mode. dll, visual-studio, debug, loadlibrary MATLAB Answers — New Questions
Issue with ARXML Importer API Not Generating All Ports and IRVs in Init Runnable in MATLAB
When using MATLAB’s ARXML Importer API (arxml.importer), why does all ports and IRVs specified in the ARXML file are not generated within the Init runnable?When using MATLAB’s ARXML Importer API (arxml.importer), why does all ports and IRVs specified in the ARXML file are not generated within the Init runnable? When using MATLAB’s ARXML Importer API (arxml.importer), why does all ports and IRVs specified in the ARXML file are not generated within the Init runnable? arxml, importer, missing, ports, init, runnable, autosar MATLAB Answers — New Questions
How do I optimize/find the minimum of a multi-variable function?
I’m trying to find the minimum of a multivariable function. I’ve tried using both fminunc and fminsearch but the results seem incorrect. I’m just confused on what I’m doing wrong and why its not working.
The data:
x=[1.0e-5;1.0e-5;1.0e-5;1.4e-5;1.4e-5;1.4e-5;1.8e-5;1.8e-5;1.8e-5];
y=[1.3e-4;1.55e-4;1.7e-4;1.3e-4;1.55e-4;1.7e-4;1.3e-4;1.55e-4;1.7e-4];
z=[18.488;21.45;24.52;20.93; 26.08; 29.41;25.44;30.98;34.19];
My code:
coeffs=fit([x,y],z,’Poly22′);
[~,idx]=min(z);
x(idx)
y(idx)
xval=fminunc(coeffs,[x(idx) y(idx)])
and
A=[x(:).^[0:2] y(:).^[1:2] x(:).*y(:)];
a=Az(:);
x2=linspace(0,2.00e-5,100);
y2=linspace(0,2.00e-4,100);
[X,Y]=meshgrid(x2,y2);
M=[X(:).^(0:2) Y(:).^(1:2) X(:).*Y(:)];
Z=X;
Z(:)=M*a;
f=@(xy) -14.19 -4.028e+05.*xy(:,1) + 2.774e+05.*xy(:,2)+ 1.473e+10.*xy(:,1).^2 + 7.05e+09.*xy(:,1).*xy(:,2) + -6.256e+08.*xy(:,2).^2;
fminsearch(f,[1.00e-5 1.55e-4])
Both methods give me results that seem incorrect. The fmincon gives me results at:
xval =
1.0e+06 *
0.324231351627941 -1.604585119026901
which based on the data, doesn’t make sense at all. What am I doing wrong?I’m trying to find the minimum of a multivariable function. I’ve tried using both fminunc and fminsearch but the results seem incorrect. I’m just confused on what I’m doing wrong and why its not working.
The data:
x=[1.0e-5;1.0e-5;1.0e-5;1.4e-5;1.4e-5;1.4e-5;1.8e-5;1.8e-5;1.8e-5];
y=[1.3e-4;1.55e-4;1.7e-4;1.3e-4;1.55e-4;1.7e-4;1.3e-4;1.55e-4;1.7e-4];
z=[18.488;21.45;24.52;20.93; 26.08; 29.41;25.44;30.98;34.19];
My code:
coeffs=fit([x,y],z,’Poly22′);
[~,idx]=min(z);
x(idx)
y(idx)
xval=fminunc(coeffs,[x(idx) y(idx)])
and
A=[x(:).^[0:2] y(:).^[1:2] x(:).*y(:)];
a=Az(:);
x2=linspace(0,2.00e-5,100);
y2=linspace(0,2.00e-4,100);
[X,Y]=meshgrid(x2,y2);
M=[X(:).^(0:2) Y(:).^(1:2) X(:).*Y(:)];
Z=X;
Z(:)=M*a;
f=@(xy) -14.19 -4.028e+05.*xy(:,1) + 2.774e+05.*xy(:,2)+ 1.473e+10.*xy(:,1).^2 + 7.05e+09.*xy(:,1).*xy(:,2) + -6.256e+08.*xy(:,2).^2;
fminsearch(f,[1.00e-5 1.55e-4])
Both methods give me results that seem incorrect. The fmincon gives me results at:
xval =
1.0e+06 *
0.324231351627941 -1.604585119026901
which based on the data, doesn’t make sense at all. What am I doing wrong? I’m trying to find the minimum of a multivariable function. I’ve tried using both fminunc and fminsearch but the results seem incorrect. I’m just confused on what I’m doing wrong and why its not working.
The data:
x=[1.0e-5;1.0e-5;1.0e-5;1.4e-5;1.4e-5;1.4e-5;1.8e-5;1.8e-5;1.8e-5];
y=[1.3e-4;1.55e-4;1.7e-4;1.3e-4;1.55e-4;1.7e-4;1.3e-4;1.55e-4;1.7e-4];
z=[18.488;21.45;24.52;20.93; 26.08; 29.41;25.44;30.98;34.19];
My code:
coeffs=fit([x,y],z,’Poly22′);
[~,idx]=min(z);
x(idx)
y(idx)
xval=fminunc(coeffs,[x(idx) y(idx)])
and
A=[x(:).^[0:2] y(:).^[1:2] x(:).*y(:)];
a=Az(:);
x2=linspace(0,2.00e-5,100);
y2=linspace(0,2.00e-4,100);
[X,Y]=meshgrid(x2,y2);
M=[X(:).^(0:2) Y(:).^(1:2) X(:).*Y(:)];
Z=X;
Z(:)=M*a;
f=@(xy) -14.19 -4.028e+05.*xy(:,1) + 2.774e+05.*xy(:,2)+ 1.473e+10.*xy(:,1).^2 + 7.05e+09.*xy(:,1).*xy(:,2) + -6.256e+08.*xy(:,2).^2;
fminsearch(f,[1.00e-5 1.55e-4])
Both methods give me results that seem incorrect. The fmincon gives me results at:
xval =
1.0e+06 *
0.324231351627941 -1.604585119026901
which based on the data, doesn’t make sense at all. What am I doing wrong? optimization, fminunc, fminsearch, matlab, functions MATLAB Answers — New Questions
Import timestamps with alternating date formats
Hello!
I have .csv data files that contain gps coordinates with timestamps. I want to import these data files into MATLAB. The problem I am having is the timestamp has an alternating date format, or at least matlab import is treating it as such. Timestamps look like:
Timestamp
16:15:29
16:15:29.500000
16:15:30
16:15:30.500000
etc.
Using import tool I can set a custom date format to HH:mm:ss.SSSSSS but this doesn’t work for the timestamps that don’t include the .SSSSSS
The import tool assigns NaT to those timestamps. Any ideas?Hello!
I have .csv data files that contain gps coordinates with timestamps. I want to import these data files into MATLAB. The problem I am having is the timestamp has an alternating date format, or at least matlab import is treating it as such. Timestamps look like:
Timestamp
16:15:29
16:15:29.500000
16:15:30
16:15:30.500000
etc.
Using import tool I can set a custom date format to HH:mm:ss.SSSSSS but this doesn’t work for the timestamps that don’t include the .SSSSSS
The import tool assigns NaT to those timestamps. Any ideas? Hello!
I have .csv data files that contain gps coordinates with timestamps. I want to import these data files into MATLAB. The problem I am having is the timestamp has an alternating date format, or at least matlab import is treating it as such. Timestamps look like:
Timestamp
16:15:29
16:15:29.500000
16:15:30
16:15:30.500000
etc.
Using import tool I can set a custom date format to HH:mm:ss.SSSSSS but this doesn’t work for the timestamps that don’t include the .SSSSSS
The import tool assigns NaT to those timestamps. Any ideas? timestamp import MATLAB Answers — New Questions
How to enable Nearest Neighbor Classifier
I would like to use "Optimizable KNN" for this training, but the whole NNC section is disabled for some reasons. Please help to solve this. The code is attached in the bottom.
% Define the file path
imageFolderPath = "C:UsersxxooxOneDriveデスクトップMATLAB worksDataMathWorks ImagesRoadside Ground Cover";
% Create an imageDatastore
imds = imageDatastore(imageFolderPath, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Display the count of each label
labelCount = countEachLabel(imds);
disp(‘Initial label count:’);
disp(labelCount);
% Split the datastore into training and testing subsets (85% training, 15% testing)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.85, ‘randomized’);
% Display the count of each label in the training datastore
labelCountTrain = countEachLabel(imdsTrain);
disp(‘Training label count:’);
disp(labelCountTrain);
% Count the images labeled as "Snow" in the training datastore
numSnowTrain = sum(imdsTrain.Labels == "Snow");
disp([‘Number of "Snow" images in the training datastore: ‘, num2str(numSnowTrain)]);
% Define the file path to the specific image
imageFilePath = fullfile(imageFolderPath, ‘No Snow’, ‘RoadsideA_1.jpg’);
% Read the image
img = imread(imageFilePath);
% Convert the image from RGB to HSV color space
hsvImage = rgb2hsv(img);
% Extract the saturation channel
saturationChannel = hsvImage(:,:,2);
% Calculate the mean saturation value
meanSaturation = mean(saturationChannel(:));
% Display the mean saturation
disp([‘The mean saturation for the "No Snow" labeled image "RoadsideA_1.jpg" is: ‘, num2str(meanSaturation)]);
% Calculate the standard deviation of the saturation values
stdSaturation = std(saturationChannel(:));
disp([‘The standard deviation of the saturation for the "No Snow" labeled image "RoadsideA_1.jpg" is: ‘, num2str(stdSaturation)]);
% Initialize arrays to store the results
fileNames = imdsTrain.Files;
labels = imdsTrain.Labels;
meanSaturations = zeros(length(fileNames), 1);
stdSaturations = zeros(length(fileNames), 1);
% Loop through each image in the training datastore
for i = 1:length(fileNames)
% Read the image
img = imread(fileNames{i});
% Convert the image from RGB to HSV color space
hsvImage = rgb2hsv(img);
% Extract the saturation channel
saturationChannel = hsvImage(:,:,2);
% Calculate the mean and standard deviation of the saturation
meanSaturations(i) = mean(saturationChannel(:));
stdSaturations(i) = std(saturationChannel(:));
end
% Create a table with the results
trainingTable = table(fileNames, labels, meanSaturations, stdSaturations, …
‘VariableNames’, {‘Filename’, ‘Label’, ‘MeanSaturation’, ‘StdSaturation’});
% Display the table
disp(trainingTable);
% Create the scatter plot
figure;
gscatter(trainingTable.MeanSaturation, trainingTable.StdSaturation, trainingTable.Label, ‘rb’, ‘ox’);
xlabel(‘Mean Saturation’);
ylabel(‘Standard Deviation of Saturation’);
title(‘Grouped Scatter Plot of Mean Saturation and Standard Deviation of Saturation’);
legend(‘No Snow’, ‘Snow’);
% Save the figure
saveas(gcf, ‘GroupedScatterPlot.png’);
% Display the result
disp(‘Scatter plot created and saved as GroupedScatterPlot.png’);I would like to use "Optimizable KNN" for this training, but the whole NNC section is disabled for some reasons. Please help to solve this. The code is attached in the bottom.
% Define the file path
imageFolderPath = "C:UsersxxooxOneDriveデスクトップMATLAB worksDataMathWorks ImagesRoadside Ground Cover";
% Create an imageDatastore
imds = imageDatastore(imageFolderPath, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Display the count of each label
labelCount = countEachLabel(imds);
disp(‘Initial label count:’);
disp(labelCount);
% Split the datastore into training and testing subsets (85% training, 15% testing)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.85, ‘randomized’);
% Display the count of each label in the training datastore
labelCountTrain = countEachLabel(imdsTrain);
disp(‘Training label count:’);
disp(labelCountTrain);
% Count the images labeled as "Snow" in the training datastore
numSnowTrain = sum(imdsTrain.Labels == "Snow");
disp([‘Number of "Snow" images in the training datastore: ‘, num2str(numSnowTrain)]);
% Define the file path to the specific image
imageFilePath = fullfile(imageFolderPath, ‘No Snow’, ‘RoadsideA_1.jpg’);
% Read the image
img = imread(imageFilePath);
% Convert the image from RGB to HSV color space
hsvImage = rgb2hsv(img);
% Extract the saturation channel
saturationChannel = hsvImage(:,:,2);
% Calculate the mean saturation value
meanSaturation = mean(saturationChannel(:));
% Display the mean saturation
disp([‘The mean saturation for the "No Snow" labeled image "RoadsideA_1.jpg" is: ‘, num2str(meanSaturation)]);
% Calculate the standard deviation of the saturation values
stdSaturation = std(saturationChannel(:));
disp([‘The standard deviation of the saturation for the "No Snow" labeled image "RoadsideA_1.jpg" is: ‘, num2str(stdSaturation)]);
% Initialize arrays to store the results
fileNames = imdsTrain.Files;
labels = imdsTrain.Labels;
meanSaturations = zeros(length(fileNames), 1);
stdSaturations = zeros(length(fileNames), 1);
% Loop through each image in the training datastore
for i = 1:length(fileNames)
% Read the image
img = imread(fileNames{i});
% Convert the image from RGB to HSV color space
hsvImage = rgb2hsv(img);
% Extract the saturation channel
saturationChannel = hsvImage(:,:,2);
% Calculate the mean and standard deviation of the saturation
meanSaturations(i) = mean(saturationChannel(:));
stdSaturations(i) = std(saturationChannel(:));
end
% Create a table with the results
trainingTable = table(fileNames, labels, meanSaturations, stdSaturations, …
‘VariableNames’, {‘Filename’, ‘Label’, ‘MeanSaturation’, ‘StdSaturation’});
% Display the table
disp(trainingTable);
% Create the scatter plot
figure;
gscatter(trainingTable.MeanSaturation, trainingTable.StdSaturation, trainingTable.Label, ‘rb’, ‘ox’);
xlabel(‘Mean Saturation’);
ylabel(‘Standard Deviation of Saturation’);
title(‘Grouped Scatter Plot of Mean Saturation and Standard Deviation of Saturation’);
legend(‘No Snow’, ‘Snow’);
% Save the figure
saveas(gcf, ‘GroupedScatterPlot.png’);
% Display the result
disp(‘Scatter plot created and saved as GroupedScatterPlot.png’); I would like to use "Optimizable KNN" for this training, but the whole NNC section is disabled for some reasons. Please help to solve this. The code is attached in the bottom.
% Define the file path
imageFolderPath = "C:UsersxxooxOneDriveデスクトップMATLAB worksDataMathWorks ImagesRoadside Ground Cover";
% Create an imageDatastore
imds = imageDatastore(imageFolderPath, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Display the count of each label
labelCount = countEachLabel(imds);
disp(‘Initial label count:’);
disp(labelCount);
% Split the datastore into training and testing subsets (85% training, 15% testing)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.85, ‘randomized’);
% Display the count of each label in the training datastore
labelCountTrain = countEachLabel(imdsTrain);
disp(‘Training label count:’);
disp(labelCountTrain);
% Count the images labeled as "Snow" in the training datastore
numSnowTrain = sum(imdsTrain.Labels == "Snow");
disp([‘Number of "Snow" images in the training datastore: ‘, num2str(numSnowTrain)]);
% Define the file path to the specific image
imageFilePath = fullfile(imageFolderPath, ‘No Snow’, ‘RoadsideA_1.jpg’);
% Read the image
img = imread(imageFilePath);
% Convert the image from RGB to HSV color space
hsvImage = rgb2hsv(img);
% Extract the saturation channel
saturationChannel = hsvImage(:,:,2);
% Calculate the mean saturation value
meanSaturation = mean(saturationChannel(:));
% Display the mean saturation
disp([‘The mean saturation for the "No Snow" labeled image "RoadsideA_1.jpg" is: ‘, num2str(meanSaturation)]);
% Calculate the standard deviation of the saturation values
stdSaturation = std(saturationChannel(:));
disp([‘The standard deviation of the saturation for the "No Snow" labeled image "RoadsideA_1.jpg" is: ‘, num2str(stdSaturation)]);
% Initialize arrays to store the results
fileNames = imdsTrain.Files;
labels = imdsTrain.Labels;
meanSaturations = zeros(length(fileNames), 1);
stdSaturations = zeros(length(fileNames), 1);
% Loop through each image in the training datastore
for i = 1:length(fileNames)
% Read the image
img = imread(fileNames{i});
% Convert the image from RGB to HSV color space
hsvImage = rgb2hsv(img);
% Extract the saturation channel
saturationChannel = hsvImage(:,:,2);
% Calculate the mean and standard deviation of the saturation
meanSaturations(i) = mean(saturationChannel(:));
stdSaturations(i) = std(saturationChannel(:));
end
% Create a table with the results
trainingTable = table(fileNames, labels, meanSaturations, stdSaturations, …
‘VariableNames’, {‘Filename’, ‘Label’, ‘MeanSaturation’, ‘StdSaturation’});
% Display the table
disp(trainingTable);
% Create the scatter plot
figure;
gscatter(trainingTable.MeanSaturation, trainingTable.StdSaturation, trainingTable.Label, ‘rb’, ‘ox’);
xlabel(‘Mean Saturation’);
ylabel(‘Standard Deviation of Saturation’);
title(‘Grouped Scatter Plot of Mean Saturation and Standard Deviation of Saturation’);
legend(‘No Snow’, ‘Snow’);
% Save the figure
saveas(gcf, ‘GroupedScatterPlot.png’);
% Display the result
disp(‘Scatter plot created and saved as GroupedScatterPlot.png’); matlab, plotting, machine learing, knn, nnc MATLAB Answers — New Questions
Create a specific colormap for a contour plot
Hi I am trying to create a contour plot with my own colormap. However, this only works up to a certain value, after which the colours are no longer output as I had hoped. From 36.8 on, everything is output in the same colour. Does anyone know why this happens?
Levels = [3200 3366 3566 3680 3700 3800]
num_points = diff(Levels);
colors = [ 0.24 0.36 0.56;
0.25 0.56 0.55;
0.45 0.82 0.26;
0.82 0.8 0.19;
0.81 0.61 0.24;
];
map = [];
for i=1:numel(num_points)
map = [map; repmat(colors(i,:), num_points(i), 1)];
end
figure( ‘Name’, ‘untitled fit 1’ , ‘Colormap’, map);
h = plot( fitresult, [xData, yData], zData, ‘Style’, ‘Contour’ );
set(h,’LevelList’,[23.4 33.6 35.6 36.8 37.0 40] , ‘ShowText’, ‘on’)Hi I am trying to create a contour plot with my own colormap. However, this only works up to a certain value, after which the colours are no longer output as I had hoped. From 36.8 on, everything is output in the same colour. Does anyone know why this happens?
Levels = [3200 3366 3566 3680 3700 3800]
num_points = diff(Levels);
colors = [ 0.24 0.36 0.56;
0.25 0.56 0.55;
0.45 0.82 0.26;
0.82 0.8 0.19;
0.81 0.61 0.24;
];
map = [];
for i=1:numel(num_points)
map = [map; repmat(colors(i,:), num_points(i), 1)];
end
figure( ‘Name’, ‘untitled fit 1’ , ‘Colormap’, map);
h = plot( fitresult, [xData, yData], zData, ‘Style’, ‘Contour’ );
set(h,’LevelList’,[23.4 33.6 35.6 36.8 37.0 40] , ‘ShowText’, ‘on’) Hi I am trying to create a contour plot with my own colormap. However, this only works up to a certain value, after which the colours are no longer output as I had hoped. From 36.8 on, everything is output in the same colour. Does anyone know why this happens?
Levels = [3200 3366 3566 3680 3700 3800]
num_points = diff(Levels);
colors = [ 0.24 0.36 0.56;
0.25 0.56 0.55;
0.45 0.82 0.26;
0.82 0.8 0.19;
0.81 0.61 0.24;
];
map = [];
for i=1:numel(num_points)
map = [map; repmat(colors(i,:), num_points(i), 1)];
end
figure( ‘Name’, ‘untitled fit 1’ , ‘Colormap’, map);
h = plot( fitresult, [xData, yData], zData, ‘Style’, ‘Contour’ );
set(h,’LevelList’,[23.4 33.6 35.6 36.8 37.0 40] , ‘ShowText’, ‘on’) colormap, contour plot, contour MATLAB Answers — New Questions