Tag Archives: matlab
Excel – refer to a sheet by name
Hello,
I need to:
(1) select a sheet by name not by Item number
(2) assign a hyperlink from a cell in a named sheet to A1 of another sheet.
for (1),I tried line 61. anything below line 61 is in progress. just trying to ‘translate’ the VBA into matlab. Any suggestions would be welcomed.
Thanks
Tuli
— code start —–
function h = excel_test_2
% OPEN EXCEL APPLICATION
excellapp = actxserver(‘Excel.Application’);
% Show the Excel window
set(excellapp, ‘Visible’, 1);
% INSERT NEW WORKBOOK
W = excellapp.Workbooks.Add;
% WORKBOOKS CONTAIN WORKSHEETS
Sheets = excellapp.ActiveWorkBook.Sheets;
% Leave just one
n = Sheets.Count;
for ii=n:-1:2
Sheets.Item(ii).Delete;
end
for ii=1:20
n = Sheets.Count;
if ii>1
Sheets.Add( [], Sheets.Item(n) );
end
Sheets.Item(ii).Name = [‘test_’ num2str(ii)];
end
% Add a fourth sheet (by default, a workbook contains
% three worksheets – add a new one before [], after #3)
Sheets.Add( [], Sheets.Item(3) );
% Rename
Sheets.Item(1).Name = ‘History Long’;
Sheets.Item(2).Name = ‘History Short’;
% Set active sheet #1
Sheets.Item(1).Activate;
ActiveSheet = excellapp.Activesheet;
% Title
ActiveSheetRange = get(ActiveSheet,’Range’,’A1′);
set(ActiveSheetRange,’Value’,’Date&Time’,…
‘ColumnWidth’,15);
set(ActiveSheetRange.Font,’FontStyle’,’Bold’,’Size’,13,’Color’,128);
% Title2
ActiveSheetRange = get(ActiveSheet,’Range’,’A2′);
set(ActiveSheetRange,’Value’,’222133013′,…
‘ColumnWidth’,15);
set(ActiveSheetRange.Font,’FontStyle’,’Bold’,’Size’,13,’Color’,128);
%———— add color change and hyperlink ———————
T10 = ‘ValueJet4’
M10 = ‘test_9’
%Range(‘A2’).Select %select cell A2 in ‘Hystory Long’
%Sheets.Item(1).Activate;
Sheets(M10).Activate;
% ActiveSheetRange = get(ActiveSheet,’Range’,’A2′);
%
% Selection.Copy % copy content of A2
%
% Sheets(M10).Select %select target sheet name
%
% Sheets(M10).Name = T10 % assign new name
%
% Sheets(T10).Select
% ActiveWorkbook.Sheets(T10).Tab.ColorIndex = 3
%
% Sheets(‘History Long’).Select
% Range(‘A2’).Select
% S10 = T10 & ‘!A1’
% ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=”, SubAddress:=S10
return
—– code end —–Hello,
I need to:
(1) select a sheet by name not by Item number
(2) assign a hyperlink from a cell in a named sheet to A1 of another sheet.
for (1),I tried line 61. anything below line 61 is in progress. just trying to ‘translate’ the VBA into matlab. Any suggestions would be welcomed.
Thanks
Tuli
— code start —–
function h = excel_test_2
% OPEN EXCEL APPLICATION
excellapp = actxserver(‘Excel.Application’);
% Show the Excel window
set(excellapp, ‘Visible’, 1);
% INSERT NEW WORKBOOK
W = excellapp.Workbooks.Add;
% WORKBOOKS CONTAIN WORKSHEETS
Sheets = excellapp.ActiveWorkBook.Sheets;
% Leave just one
n = Sheets.Count;
for ii=n:-1:2
Sheets.Item(ii).Delete;
end
for ii=1:20
n = Sheets.Count;
if ii>1
Sheets.Add( [], Sheets.Item(n) );
end
Sheets.Item(ii).Name = [‘test_’ num2str(ii)];
end
% Add a fourth sheet (by default, a workbook contains
% three worksheets – add a new one before [], after #3)
Sheets.Add( [], Sheets.Item(3) );
% Rename
Sheets.Item(1).Name = ‘History Long’;
Sheets.Item(2).Name = ‘History Short’;
% Set active sheet #1
Sheets.Item(1).Activate;
ActiveSheet = excellapp.Activesheet;
% Title
ActiveSheetRange = get(ActiveSheet,’Range’,’A1′);
set(ActiveSheetRange,’Value’,’Date&Time’,…
‘ColumnWidth’,15);
set(ActiveSheetRange.Font,’FontStyle’,’Bold’,’Size’,13,’Color’,128);
% Title2
ActiveSheetRange = get(ActiveSheet,’Range’,’A2′);
set(ActiveSheetRange,’Value’,’222133013′,…
‘ColumnWidth’,15);
set(ActiveSheetRange.Font,’FontStyle’,’Bold’,’Size’,13,’Color’,128);
%———— add color change and hyperlink ———————
T10 = ‘ValueJet4’
M10 = ‘test_9’
%Range(‘A2’).Select %select cell A2 in ‘Hystory Long’
%Sheets.Item(1).Activate;
Sheets(M10).Activate;
% ActiveSheetRange = get(ActiveSheet,’Range’,’A2′);
%
% Selection.Copy % copy content of A2
%
% Sheets(M10).Select %select target sheet name
%
% Sheets(M10).Name = T10 % assign new name
%
% Sheets(T10).Select
% ActiveWorkbook.Sheets(T10).Tab.ColorIndex = 3
%
% Sheets(‘History Long’).Select
% Range(‘A2’).Select
% S10 = T10 & ‘!A1’
% ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=”, SubAddress:=S10
return
—– code end —– Hello,
I need to:
(1) select a sheet by name not by Item number
(2) assign a hyperlink from a cell in a named sheet to A1 of another sheet.
for (1),I tried line 61. anything below line 61 is in progress. just trying to ‘translate’ the VBA into matlab. Any suggestions would be welcomed.
Thanks
Tuli
— code start —–
function h = excel_test_2
% OPEN EXCEL APPLICATION
excellapp = actxserver(‘Excel.Application’);
% Show the Excel window
set(excellapp, ‘Visible’, 1);
% INSERT NEW WORKBOOK
W = excellapp.Workbooks.Add;
% WORKBOOKS CONTAIN WORKSHEETS
Sheets = excellapp.ActiveWorkBook.Sheets;
% Leave just one
n = Sheets.Count;
for ii=n:-1:2
Sheets.Item(ii).Delete;
end
for ii=1:20
n = Sheets.Count;
if ii>1
Sheets.Add( [], Sheets.Item(n) );
end
Sheets.Item(ii).Name = [‘test_’ num2str(ii)];
end
% Add a fourth sheet (by default, a workbook contains
% three worksheets – add a new one before [], after #3)
Sheets.Add( [], Sheets.Item(3) );
% Rename
Sheets.Item(1).Name = ‘History Long’;
Sheets.Item(2).Name = ‘History Short’;
% Set active sheet #1
Sheets.Item(1).Activate;
ActiveSheet = excellapp.Activesheet;
% Title
ActiveSheetRange = get(ActiveSheet,’Range’,’A1′);
set(ActiveSheetRange,’Value’,’Date&Time’,…
‘ColumnWidth’,15);
set(ActiveSheetRange.Font,’FontStyle’,’Bold’,’Size’,13,’Color’,128);
% Title2
ActiveSheetRange = get(ActiveSheet,’Range’,’A2′);
set(ActiveSheetRange,’Value’,’222133013′,…
‘ColumnWidth’,15);
set(ActiveSheetRange.Font,’FontStyle’,’Bold’,’Size’,13,’Color’,128);
%———— add color change and hyperlink ———————
T10 = ‘ValueJet4’
M10 = ‘test_9’
%Range(‘A2’).Select %select cell A2 in ‘Hystory Long’
%Sheets.Item(1).Activate;
Sheets(M10).Activate;
% ActiveSheetRange = get(ActiveSheet,’Range’,’A2′);
%
% Selection.Copy % copy content of A2
%
% Sheets(M10).Select %select target sheet name
%
% Sheets(M10).Name = T10 % assign new name
%
% Sheets(T10).Select
% ActiveWorkbook.Sheets(T10).Tab.ColorIndex = 3
%
% Sheets(‘History Long’).Select
% Range(‘A2’).Select
% S10 = T10 & ‘!A1’
% ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=”, SubAddress:=S10
return
—– code end —– control excel hyperlink MATLAB Answers — New Questions
In Simulink, why do two unrelated modules affect each other?
In Simulink, I created two computation modules A and B, as shown in Figure 1. Modules A and B are independent of each other and do not share any data. When A and B are not connected, the time history chart calculated by Module A is shown in Figure 1. However, when A is connected to B, Module A calculates a different time history chart, as shown in Figure 2. Note that Module B does not form a closed-loop with Module A. Why does this situation occur? I would appreciate it if anyone could tell me the reason, thank you very much.
Additionally, I found that as long as module A is connected with the transfer function module (without forming a closed-loop circuit), the time course graph on the oscilloscope will change.In Simulink, I created two computation modules A and B, as shown in Figure 1. Modules A and B are independent of each other and do not share any data. When A and B are not connected, the time history chart calculated by Module A is shown in Figure 1. However, when A is connected to B, Module A calculates a different time history chart, as shown in Figure 2. Note that Module B does not form a closed-loop with Module A. Why does this situation occur? I would appreciate it if anyone could tell me the reason, thank you very much.
Additionally, I found that as long as module A is connected with the transfer function module (without forming a closed-loop circuit), the time course graph on the oscilloscope will change. In Simulink, I created two computation modules A and B, as shown in Figure 1. Modules A and B are independent of each other and do not share any data. When A and B are not connected, the time history chart calculated by Module A is shown in Figure 1. However, when A is connected to B, Module A calculates a different time history chart, as shown in Figure 2. Note that Module B does not form a closed-loop with Module A. Why does this situation occur? I would appreciate it if anyone could tell me the reason, thank you very much.
Additionally, I found that as long as module A is connected with the transfer function module (without forming a closed-loop circuit), the time course graph on the oscilloscope will change. module, interact, simulink MATLAB Answers — New Questions
libstdc++.so.6: __cxa_thread_atexit_impl: invalid needed version 54
I got the error as show in my quesiton while I’m compling a fortran program on linux using matlab mex and libraries: libstdc++.so.6: __cxa_thread_atexit_impl: invalid needed version 54. Could some one help resolve this problem? Thank you!I got the error as show in my quesiton while I’m compling a fortran program on linux using matlab mex and libraries: libstdc++.so.6: __cxa_thread_atexit_impl: invalid needed version 54. Could some one help resolve this problem? Thank you! I got the error as show in my quesiton while I’m compling a fortran program on linux using matlab mex and libraries: libstdc++.so.6: __cxa_thread_atexit_impl: invalid needed version 54. Could some one help resolve this problem? Thank you! libstdc++.so MATLAB Answers — New Questions
creating loop that stops at correct formula for the given input.
I am writting a program the finds the polynomial using the least-square method and Gausian elimination and from there displays the correct polynomial equation. The code for the least-square and the Gaussian elimination works fine, where I am having trouble is at the end getting the display of the polynomial equation depending on what value of "n" you show correcty and nothing lower then or higher then the corresponding the chosen value of "n". What loop would for best to do this? My fist thought is and if else loop but how would I set this up to run correctly?
clear, close, clc
%input
x=[0 1 2 3 4 5];
y=[2.1 7.7 13.6 27.2 40.9 61.1];
n=8; %order of the polynomial you want to find
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION
x=x; %x-cordinates from data-input; independent vairiables
y=y; %y-cordinates from data-output; dependent vairiables
%CALCULATIONS SECTION
k=length(x); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(x.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(y.*x.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%
%STANDARD DEVIATION
Y_bar=mean(y); %ADVERAGE OF y
St=sum((y-Y_bar).^2);
SD=sqrt(St/(k-1)); %STANDARD DEVIATION
%STANDARD ERROR
for i=1:m;
T(:,i)=a(i)*x.^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
end
for i=1:k
y_hat(i)=sum(T(i,:));
end
Sr=sum((y-y_hat).^2);
Se=sqrt(Sr/(k-(n+1))); %STANDARD ERROR-Se
%COEFFICIENT OF DETERMINATION
Cd=(St-Sr)/St %COEFFICIENT OF DETERMINATION (r^2)
fprintf(‘For n=%d. Coefficient of Determination=%0.5fn’,n,Cd)
%EQUATION FOR THE POLYNOMIAL
syms x y
for n=1
a0=a(:,1);a1=a(:,2);a2=a(:,3);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2
end
for n=2
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3
end
for n=3
a0=a(:,1);a1=a(:,2);a2=a(:,2);a3=a(:,4);a4=a(:,5);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4
end
for n=4
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5
end
for n=5
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7)
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6
end
for n=6
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7
end
for n=7
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8
end
for n=8
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9
end
for n=9
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);a10=a(:,11);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9+a10*x.^10
endI am writting a program the finds the polynomial using the least-square method and Gausian elimination and from there displays the correct polynomial equation. The code for the least-square and the Gaussian elimination works fine, where I am having trouble is at the end getting the display of the polynomial equation depending on what value of "n" you show correcty and nothing lower then or higher then the corresponding the chosen value of "n". What loop would for best to do this? My fist thought is and if else loop but how would I set this up to run correctly?
clear, close, clc
%input
x=[0 1 2 3 4 5];
y=[2.1 7.7 13.6 27.2 40.9 61.1];
n=8; %order of the polynomial you want to find
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION
x=x; %x-cordinates from data-input; independent vairiables
y=y; %y-cordinates from data-output; dependent vairiables
%CALCULATIONS SECTION
k=length(x); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(x.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(y.*x.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%
%STANDARD DEVIATION
Y_bar=mean(y); %ADVERAGE OF y
St=sum((y-Y_bar).^2);
SD=sqrt(St/(k-1)); %STANDARD DEVIATION
%STANDARD ERROR
for i=1:m;
T(:,i)=a(i)*x.^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
end
for i=1:k
y_hat(i)=sum(T(i,:));
end
Sr=sum((y-y_hat).^2);
Se=sqrt(Sr/(k-(n+1))); %STANDARD ERROR-Se
%COEFFICIENT OF DETERMINATION
Cd=(St-Sr)/St %COEFFICIENT OF DETERMINATION (r^2)
fprintf(‘For n=%d. Coefficient of Determination=%0.5fn’,n,Cd)
%EQUATION FOR THE POLYNOMIAL
syms x y
for n=1
a0=a(:,1);a1=a(:,2);a2=a(:,3);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2
end
for n=2
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3
end
for n=3
a0=a(:,1);a1=a(:,2);a2=a(:,2);a3=a(:,4);a4=a(:,5);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4
end
for n=4
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5
end
for n=5
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7)
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6
end
for n=6
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7
end
for n=7
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8
end
for n=8
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9
end
for n=9
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);a10=a(:,11);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9+a10*x.^10
end I am writting a program the finds the polynomial using the least-square method and Gausian elimination and from there displays the correct polynomial equation. The code for the least-square and the Gaussian elimination works fine, where I am having trouble is at the end getting the display of the polynomial equation depending on what value of "n" you show correcty and nothing lower then or higher then the corresponding the chosen value of "n". What loop would for best to do this? My fist thought is and if else loop but how would I set this up to run correctly?
clear, close, clc
%input
x=[0 1 2 3 4 5];
y=[2.1 7.7 13.6 27.2 40.9 61.1];
n=8; %order of the polynomial you want to find
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION
x=x; %x-cordinates from data-input; independent vairiables
y=y; %y-cordinates from data-output; dependent vairiables
%CALCULATIONS SECTION
k=length(x); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(x.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(y.*x.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%
%STANDARD DEVIATION
Y_bar=mean(y); %ADVERAGE OF y
St=sum((y-Y_bar).^2);
SD=sqrt(St/(k-1)); %STANDARD DEVIATION
%STANDARD ERROR
for i=1:m;
T(:,i)=a(i)*x.^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
end
for i=1:k
y_hat(i)=sum(T(i,:));
end
Sr=sum((y-y_hat).^2);
Se=sqrt(Sr/(k-(n+1))); %STANDARD ERROR-Se
%COEFFICIENT OF DETERMINATION
Cd=(St-Sr)/St %COEFFICIENT OF DETERMINATION (r^2)
fprintf(‘For n=%d. Coefficient of Determination=%0.5fn’,n,Cd)
%EQUATION FOR THE POLYNOMIAL
syms x y
for n=1
a0=a(:,1);a1=a(:,2);a2=a(:,3);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2
end
for n=2
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3
end
for n=3
a0=a(:,1);a1=a(:,2);a2=a(:,2);a3=a(:,4);a4=a(:,5);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4
end
for n=4
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5
end
for n=5
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7)
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6
end
for n=6
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7
end
for n=7
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8
end
for n=8
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9
end
for n=9
a0=a(:,1);a1=a(:,2);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);a10=a(:,11);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9+a10*x.^10
end loop to display equation for changing input, loop MATLAB Answers — New Questions
Nonlinear constraint not satisfied for paretosearch
Hi community,
I am using paretosearch for a 2-objective optimization problem to maximize them. Based on hardcoded values, I know objective #2 can be at least . So I want to make it a constraint that in the constraint function, I specify objective #2 has to be greater than , which I know it can be achieved. But after I run the algorithm and get the pareto front, there are points on the pareto front whose objective #2 is lower than the constrainted value, why this is the case?
As shown in the attached picture, I already set a constraint that objective #2 has to be greater than . But the pareto front still has the points that are lower than . Why this is the case? Can I not set the constraint this way?
I am setting this constraint in the mindset that I want the solver to explore more in this direction.
Thank you!
XiaoweiHi community,
I am using paretosearch for a 2-objective optimization problem to maximize them. Based on hardcoded values, I know objective #2 can be at least . So I want to make it a constraint that in the constraint function, I specify objective #2 has to be greater than , which I know it can be achieved. But after I run the algorithm and get the pareto front, there are points on the pareto front whose objective #2 is lower than the constrainted value, why this is the case?
As shown in the attached picture, I already set a constraint that objective #2 has to be greater than . But the pareto front still has the points that are lower than . Why this is the case? Can I not set the constraint this way?
I am setting this constraint in the mindset that I want the solver to explore more in this direction.
Thank you!
Xiaowei Hi community,
I am using paretosearch for a 2-objective optimization problem to maximize them. Based on hardcoded values, I know objective #2 can be at least . So I want to make it a constraint that in the constraint function, I specify objective #2 has to be greater than , which I know it can be achieved. But after I run the algorithm and get the pareto front, there are points on the pareto front whose objective #2 is lower than the constrainted value, why this is the case?
As shown in the attached picture, I already set a constraint that objective #2 has to be greater than . But the pareto front still has the points that are lower than . Why this is the case? Can I not set the constraint this way?
I am setting this constraint in the mindset that I want the solver to explore more in this direction.
Thank you!
Xiaowei optimization, nonlinear MATLAB Answers — New Questions
MSSA method multichannel spectrum analysis
How we can use multichannel spectrum analysis with time series contain temporal and spatial data :time, latitude , longitude ?
the time is daily-based data , lat-log is 2.5x 5 degrees ???How we can use multichannel spectrum analysis with time series contain temporal and spatial data :time, latitude , longitude ?
the time is daily-based data , lat-log is 2.5x 5 degrees ??? How we can use multichannel spectrum analysis with time series contain temporal and spatial data :time, latitude , longitude ?
the time is daily-based data , lat-log is 2.5x 5 degrees ??? multichannel singular spectrum MATLAB Answers — New Questions
Output single Timetable from Simulink when some logged signals are not doubles
I would like, for conveneince, to have one timetable output from Simulink. Some of my signals are logical and I don’t want to make them doubles because that incorrectly captures what they are supposed to be. However, when I try to log these signals to a single timetable using extractTimetable(simout.logsout)
Error using matlab.internal.tabular.extractTimetable (line 300)
Unable to synchronize the specified data. To output data as a cell array, set ‘OutputFormat’ to ‘cell-by-signal’.
Error in Simulink.SimulationData.Dataset/extractTimetable
(…)
Caused by:
Error using timetable/synchronize (line 343)
All variables in input timetables must support missing values (e.g. floating point, categorical, datetime, duration, or text) when synchronizing using ‘fillwithmissing’.
As far as I can tell, it is because extractTimetable synchronizes everything with a specific option, fillWithNaN. Is there a way to change this behavior to allow logical values to be used? fillwithconstant would be my preference – but it is moot because my simulations do not have missing values!I would like, for conveneince, to have one timetable output from Simulink. Some of my signals are logical and I don’t want to make them doubles because that incorrectly captures what they are supposed to be. However, when I try to log these signals to a single timetable using extractTimetable(simout.logsout)
Error using matlab.internal.tabular.extractTimetable (line 300)
Unable to synchronize the specified data. To output data as a cell array, set ‘OutputFormat’ to ‘cell-by-signal’.
Error in Simulink.SimulationData.Dataset/extractTimetable
(…)
Caused by:
Error using timetable/synchronize (line 343)
All variables in input timetables must support missing values (e.g. floating point, categorical, datetime, duration, or text) when synchronizing using ‘fillwithmissing’.
As far as I can tell, it is because extractTimetable synchronizes everything with a specific option, fillWithNaN. Is there a way to change this behavior to allow logical values to be used? fillwithconstant would be my preference – but it is moot because my simulations do not have missing values! I would like, for conveneince, to have one timetable output from Simulink. Some of my signals are logical and I don’t want to make them doubles because that incorrectly captures what they are supposed to be. However, when I try to log these signals to a single timetable using extractTimetable(simout.logsout)
Error using matlab.internal.tabular.extractTimetable (line 300)
Unable to synchronize the specified data. To output data as a cell array, set ‘OutputFormat’ to ‘cell-by-signal’.
Error in Simulink.SimulationData.Dataset/extractTimetable
(…)
Caused by:
Error using timetable/synchronize (line 343)
All variables in input timetables must support missing values (e.g. floating point, categorical, datetime, duration, or text) when synchronizing using ‘fillwithmissing’.
As far as I can tell, it is because extractTimetable synchronizes everything with a specific option, fillWithNaN. Is there a way to change this behavior to allow logical values to be used? fillwithconstant would be my preference – but it is moot because my simulations do not have missing values! simulink, logging, timetable MATLAB Answers — New Questions
Experiment Manager stucks on “Stopping Trial”
I am sweeping hyper parameters used for training an RL agent. everything is fine until I try to use the "Stop" botton on the top to stop the whole experiment, or when I click on "stop" button of each of the individual trainings. It stucks, and in the background I can see the timer for that training still increasing. Even when I try to close the manager using the X button, it tells me "Experiment is currently running" Stop running the experiment?" what is the problem here. It looks like a bug in the software to me.I am sweeping hyper parameters used for training an RL agent. everything is fine until I try to use the "Stop" botton on the top to stop the whole experiment, or when I click on "stop" button of each of the individual trainings. It stucks, and in the background I can see the timer for that training still increasing. Even when I try to close the manager using the X button, it tells me "Experiment is currently running" Stop running the experiment?" what is the problem here. It looks like a bug in the software to me. I am sweeping hyper parameters used for training an RL agent. everything is fine until I try to use the "Stop" botton on the top to stop the whole experiment, or when I click on "stop" button of each of the individual trainings. It stucks, and in the background I can see the timer for that training still increasing. Even when I try to close the manager using the X button, it tells me "Experiment is currently running" Stop running the experiment?" what is the problem here. It looks like a bug in the software to me. experiment manager, hyper parameter sweep MATLAB Answers — New Questions
Callback error for Serialport
Using App Designer on Win10
I successfully open a serial port, communicate with my Pico Arduino doing a handshake that verifies that I have the correct device.
But when I put in the callback function for received data it sends a warning to the MatLab Command window many seconds AFTER StartupFcn completes. (Got "Setup Done" to debug text window I made)
Warning:
Warning: Error executing listener callback for PostSet event on TotalBytesWritten dynamic property
in object of matlabshared.asyncio.internal.Channel class:
Undefined function ‘PicoInput’ for input arguments of type ‘internal.Serialport’.
After that it sends this error to the command window every few seconds:
Warning: Error executing listener callback for PostSet event on TotalBytesWritten dynamic property
in object of matlabshared.asyncio.internal.Channel class:
Undefined function ‘PicoInput’ for input arguments of type ‘internal.Serialport’.
Error in internal.Serialport/callbackFunction (line 1472)
obj.BytesAvailableFcn(obj, dataAvailableInfo);
Error in internal.Serialport>@(varargin)obj.callbackFunction(varargin{:}) (line 980)
obj.StringClient.StringReadFcn = @obj.callbackFunction;
Error in matlabshared.transportclients.internal.StringClient.StringClient/DataAvailableCallback
Error in
matlabshared.transportclients.internal.StringClient.StringClient>@(varargin)obj.DataAvailableCallback(varargin{:})
Error in matlabshared.transportlib.internal.DataReceivedHandlerMixin/valuesWrittenUpdated
Error in
matlabshared.transportlib.internal.DataReceivedHandlerMixin>@(src,evt)obj.valuesWrittenUpdated(src,evt)
Error in matlabshared.asyncio.internal.Channel/onPropertyChanged (line 569)
obj.(name) = value;
Error in
matlabshared.asyncio.internal.Channel>@(source,data)obj.onPropertyChanged(data.Name,data.Value)
(line 465)
@(source, data) obj.onPropertyChanged(data.Name,
data.Value));
> In matlabshared.asyncio.internal/Channel/onPropertyChanged (line 569)
In matlabshared.asyncio.internal.Channel>@(source,data)obj.onPropertyChanged(data.Name,data.Value) (line 465)
>>
Nothing is being sent or received
The GUI figure keeps running until I try to send a command then the App Designer debugger closes (goes back to Run from Step) though the app stays open and keeps running (other callbacks still work)
One odd thing is that it shouldn’t even be activating the callback since nothing is coming in.
I only need the callback for received messages, output commands to Pico are sent from other functions and callbacks.
StartupFcn Code:
function startupFcn(app)
% init vars to default start values
% (probably not needed as one can usually call .Value property)
app.ITImax = app.ITI_maxSpinner.Value;
app.ITImin = app.ITI_minSpinner.Value;
app.OdorTm = app.OdorDurationsSpinner.Value;
app.EndSndTm = app.EndSoundDurSpinner.Value;
app.ErrorSndTm = app.ErrorSoundSpinner.Value;
app.VlvOTm = app.ValOpenTimeSpinner.Value;
% init find and the serial port
ports = serialportlist("available");
% There’s the mouse on Com1 so are there more Coms?
if size(ports,2)==2 % 2 cols so 2 or more S ports
app.PicoCom = serialport(ports(1,2),115200); % attach port
configureTerminator(app.PicoCom,"CR/LF"); % What Pico does
% send ID to see if we have correct "instrument"
flush(app.PicoCom); % start clean
write(app.PicoCom,’i’,’char’); % prompt for id
pause(0.02); % Need a delay? Why not? USB or Pico could be slow
if app.PicoCom.NumBytesAvailable > 1 % got something
idData = read(app.PicoCom,2,’char’);
if ~ischar(idData) % must be a char array unless
warningMessage = …
sprintf(‘Warning: Pico not found. Maybe another USB device at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
return;
end
else % no answer
idData = ‘ ‘; % No ID data
warningMessage = …
sprintf(‘Warning: Pico not responding at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
return;
end
% ok, got a 2 char string…
if strcmp(idData,’#1′) % There’s my baby
flush(app.PicoCom); % clear Serial input and output buffers
write(app.PicoCom,’d’,’char’); % gotya – Pico can move on
% Set callback to handle future inputs from Pico
app.PicoCom.configureCallback("terminator",@PicoInput);
else % wrong answer
warningMessage = sprintf(…
‘Warning: Pico not found. There is another USB device at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
end
else
warningMessage = sprintf(‘Warning: No Serial devices found.’);
uiwait(msgbox(warningMessage));
end
app.DebugText.Value = "Setup done";
% about to end startupFcn
end
Output Function:
% Output to Pico
function CmdToPico(app,toPicoStr)
% app.DebugText.Value = toPicoStr;
write(app.PicoCom, toPicoStr, "string");
end
Here is PicoInput callback: (I can’t add anything after the next code section. It’s at the bottom of this window! Probably enough info, but ask if you need more.
% callback for serial line input from Pico
function PicoInput(app,src,~) % don’t need event?
raw = readline(src); % src.UserData??
if raw{1}==’#’ % A debug line from Pic0
app.DebugText.Value = raw;
else
app.PicoType = raw{1}; % first char always "type"
app.PicoData = str2double(raw{2:end}); % numeric data starts at second char
app.PicoData = uint16(app.PicoData); % save as integer
% Show Pico Dat String after parsing
PicoS = sprintf("Char: %c Value: %d", app.PicoType, app.PicoData);
app.DebugText.Value = PicoS;
end
endUsing App Designer on Win10
I successfully open a serial port, communicate with my Pico Arduino doing a handshake that verifies that I have the correct device.
But when I put in the callback function for received data it sends a warning to the MatLab Command window many seconds AFTER StartupFcn completes. (Got "Setup Done" to debug text window I made)
Warning:
Warning: Error executing listener callback for PostSet event on TotalBytesWritten dynamic property
in object of matlabshared.asyncio.internal.Channel class:
Undefined function ‘PicoInput’ for input arguments of type ‘internal.Serialport’.
After that it sends this error to the command window every few seconds:
Warning: Error executing listener callback for PostSet event on TotalBytesWritten dynamic property
in object of matlabshared.asyncio.internal.Channel class:
Undefined function ‘PicoInput’ for input arguments of type ‘internal.Serialport’.
Error in internal.Serialport/callbackFunction (line 1472)
obj.BytesAvailableFcn(obj, dataAvailableInfo);
Error in internal.Serialport>@(varargin)obj.callbackFunction(varargin{:}) (line 980)
obj.StringClient.StringReadFcn = @obj.callbackFunction;
Error in matlabshared.transportclients.internal.StringClient.StringClient/DataAvailableCallback
Error in
matlabshared.transportclients.internal.StringClient.StringClient>@(varargin)obj.DataAvailableCallback(varargin{:})
Error in matlabshared.transportlib.internal.DataReceivedHandlerMixin/valuesWrittenUpdated
Error in
matlabshared.transportlib.internal.DataReceivedHandlerMixin>@(src,evt)obj.valuesWrittenUpdated(src,evt)
Error in matlabshared.asyncio.internal.Channel/onPropertyChanged (line 569)
obj.(name) = value;
Error in
matlabshared.asyncio.internal.Channel>@(source,data)obj.onPropertyChanged(data.Name,data.Value)
(line 465)
@(source, data) obj.onPropertyChanged(data.Name,
data.Value));
> In matlabshared.asyncio.internal/Channel/onPropertyChanged (line 569)
In matlabshared.asyncio.internal.Channel>@(source,data)obj.onPropertyChanged(data.Name,data.Value) (line 465)
>>
Nothing is being sent or received
The GUI figure keeps running until I try to send a command then the App Designer debugger closes (goes back to Run from Step) though the app stays open and keeps running (other callbacks still work)
One odd thing is that it shouldn’t even be activating the callback since nothing is coming in.
I only need the callback for received messages, output commands to Pico are sent from other functions and callbacks.
StartupFcn Code:
function startupFcn(app)
% init vars to default start values
% (probably not needed as one can usually call .Value property)
app.ITImax = app.ITI_maxSpinner.Value;
app.ITImin = app.ITI_minSpinner.Value;
app.OdorTm = app.OdorDurationsSpinner.Value;
app.EndSndTm = app.EndSoundDurSpinner.Value;
app.ErrorSndTm = app.ErrorSoundSpinner.Value;
app.VlvOTm = app.ValOpenTimeSpinner.Value;
% init find and the serial port
ports = serialportlist("available");
% There’s the mouse on Com1 so are there more Coms?
if size(ports,2)==2 % 2 cols so 2 or more S ports
app.PicoCom = serialport(ports(1,2),115200); % attach port
configureTerminator(app.PicoCom,"CR/LF"); % What Pico does
% send ID to see if we have correct "instrument"
flush(app.PicoCom); % start clean
write(app.PicoCom,’i’,’char’); % prompt for id
pause(0.02); % Need a delay? Why not? USB or Pico could be slow
if app.PicoCom.NumBytesAvailable > 1 % got something
idData = read(app.PicoCom,2,’char’);
if ~ischar(idData) % must be a char array unless
warningMessage = …
sprintf(‘Warning: Pico not found. Maybe another USB device at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
return;
end
else % no answer
idData = ‘ ‘; % No ID data
warningMessage = …
sprintf(‘Warning: Pico not responding at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
return;
end
% ok, got a 2 char string…
if strcmp(idData,’#1′) % There’s my baby
flush(app.PicoCom); % clear Serial input and output buffers
write(app.PicoCom,’d’,’char’); % gotya – Pico can move on
% Set callback to handle future inputs from Pico
app.PicoCom.configureCallback("terminator",@PicoInput);
else % wrong answer
warningMessage = sprintf(…
‘Warning: Pico not found. There is another USB device at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
end
else
warningMessage = sprintf(‘Warning: No Serial devices found.’);
uiwait(msgbox(warningMessage));
end
app.DebugText.Value = "Setup done";
% about to end startupFcn
end
Output Function:
% Output to Pico
function CmdToPico(app,toPicoStr)
% app.DebugText.Value = toPicoStr;
write(app.PicoCom, toPicoStr, "string");
end
Here is PicoInput callback: (I can’t add anything after the next code section. It’s at the bottom of this window! Probably enough info, but ask if you need more.
% callback for serial line input from Pico
function PicoInput(app,src,~) % don’t need event?
raw = readline(src); % src.UserData??
if raw{1}==’#’ % A debug line from Pic0
app.DebugText.Value = raw;
else
app.PicoType = raw{1}; % first char always "type"
app.PicoData = str2double(raw{2:end}); % numeric data starts at second char
app.PicoData = uint16(app.PicoData); % save as integer
% Show Pico Dat String after parsing
PicoS = sprintf("Char: %c Value: %d", app.PicoType, app.PicoData);
app.DebugText.Value = PicoS;
end
end Using App Designer on Win10
I successfully open a serial port, communicate with my Pico Arduino doing a handshake that verifies that I have the correct device.
But when I put in the callback function for received data it sends a warning to the MatLab Command window many seconds AFTER StartupFcn completes. (Got "Setup Done" to debug text window I made)
Warning:
Warning: Error executing listener callback for PostSet event on TotalBytesWritten dynamic property
in object of matlabshared.asyncio.internal.Channel class:
Undefined function ‘PicoInput’ for input arguments of type ‘internal.Serialport’.
After that it sends this error to the command window every few seconds:
Warning: Error executing listener callback for PostSet event on TotalBytesWritten dynamic property
in object of matlabshared.asyncio.internal.Channel class:
Undefined function ‘PicoInput’ for input arguments of type ‘internal.Serialport’.
Error in internal.Serialport/callbackFunction (line 1472)
obj.BytesAvailableFcn(obj, dataAvailableInfo);
Error in internal.Serialport>@(varargin)obj.callbackFunction(varargin{:}) (line 980)
obj.StringClient.StringReadFcn = @obj.callbackFunction;
Error in matlabshared.transportclients.internal.StringClient.StringClient/DataAvailableCallback
Error in
matlabshared.transportclients.internal.StringClient.StringClient>@(varargin)obj.DataAvailableCallback(varargin{:})
Error in matlabshared.transportlib.internal.DataReceivedHandlerMixin/valuesWrittenUpdated
Error in
matlabshared.transportlib.internal.DataReceivedHandlerMixin>@(src,evt)obj.valuesWrittenUpdated(src,evt)
Error in matlabshared.asyncio.internal.Channel/onPropertyChanged (line 569)
obj.(name) = value;
Error in
matlabshared.asyncio.internal.Channel>@(source,data)obj.onPropertyChanged(data.Name,data.Value)
(line 465)
@(source, data) obj.onPropertyChanged(data.Name,
data.Value));
> In matlabshared.asyncio.internal/Channel/onPropertyChanged (line 569)
In matlabshared.asyncio.internal.Channel>@(source,data)obj.onPropertyChanged(data.Name,data.Value) (line 465)
>>
Nothing is being sent or received
The GUI figure keeps running until I try to send a command then the App Designer debugger closes (goes back to Run from Step) though the app stays open and keeps running (other callbacks still work)
One odd thing is that it shouldn’t even be activating the callback since nothing is coming in.
I only need the callback for received messages, output commands to Pico are sent from other functions and callbacks.
StartupFcn Code:
function startupFcn(app)
% init vars to default start values
% (probably not needed as one can usually call .Value property)
app.ITImax = app.ITI_maxSpinner.Value;
app.ITImin = app.ITI_minSpinner.Value;
app.OdorTm = app.OdorDurationsSpinner.Value;
app.EndSndTm = app.EndSoundDurSpinner.Value;
app.ErrorSndTm = app.ErrorSoundSpinner.Value;
app.VlvOTm = app.ValOpenTimeSpinner.Value;
% init find and the serial port
ports = serialportlist("available");
% There’s the mouse on Com1 so are there more Coms?
if size(ports,2)==2 % 2 cols so 2 or more S ports
app.PicoCom = serialport(ports(1,2),115200); % attach port
configureTerminator(app.PicoCom,"CR/LF"); % What Pico does
% send ID to see if we have correct "instrument"
flush(app.PicoCom); % start clean
write(app.PicoCom,’i’,’char’); % prompt for id
pause(0.02); % Need a delay? Why not? USB or Pico could be slow
if app.PicoCom.NumBytesAvailable > 1 % got something
idData = read(app.PicoCom,2,’char’);
if ~ischar(idData) % must be a char array unless
warningMessage = …
sprintf(‘Warning: Pico not found. Maybe another USB device at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
return;
end
else % no answer
idData = ‘ ‘; % No ID data
warningMessage = …
sprintf(‘Warning: Pico not responding at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
return;
end
% ok, got a 2 char string…
if strcmp(idData,’#1′) % There’s my baby
flush(app.PicoCom); % clear Serial input and output buffers
write(app.PicoCom,’d’,’char’); % gotya – Pico can move on
% Set callback to handle future inputs from Pico
app.PicoCom.configureCallback("terminator",@PicoInput);
else % wrong answer
warningMessage = sprintf(…
‘Warning: Pico not found. There is another USB device at %s’,app.PicoCom.Port);
uiwait(msgbox(warningMessage));
end
else
warningMessage = sprintf(‘Warning: No Serial devices found.’);
uiwait(msgbox(warningMessage));
end
app.DebugText.Value = "Setup done";
% about to end startupFcn
end
Output Function:
% Output to Pico
function CmdToPico(app,toPicoStr)
% app.DebugText.Value = toPicoStr;
write(app.PicoCom, toPicoStr, "string");
end
Here is PicoInput callback: (I can’t add anything after the next code section. It’s at the bottom of this window! Probably enough info, but ask if you need more.
% callback for serial line input from Pico
function PicoInput(app,src,~) % don’t need event?
raw = readline(src); % src.UserData??
if raw{1}==’#’ % A debug line from Pic0
app.DebugText.Value = raw;
else
app.PicoType = raw{1}; % first char always "type"
app.PicoData = str2double(raw{2:end}); % numeric data starts at second char
app.PicoData = uint16(app.PicoData); % save as integer
% Show Pico Dat String after parsing
PicoS = sprintf("Char: %c Value: %d", app.PicoType, app.PicoData);
app.DebugText.Value = PicoS;
end
end serial callback, configurecallback MATLAB Answers — New Questions
trainNetwork image train error
I am tryeing to train neural network training images.
My code is based on this article: https://blogs.mathworks.com/deep-learning/2021/05/10/semantic-segmentation-for-medical-imaging/#respond
Here is complete code of my script:
% Clear workspace
clear; close all; clc;
% Specify the directory path you want to delete
directoryPath = ‘training_images/resized’;
% Check if the directory exists before trying to delete it
if exist(directoryPath, ‘dir’)
% Remove the directory and its contents
[status, message, messageId] = rmdir(directoryPath, ‘s’);
% Check if the operation was successful
if status
disp([‘Directory "’, directoryPath, ‘" has been deleted successfully.’]);
else
disp([‘Failed to delete "’, directoryPath, ‘": ‘, message]);
end
else
disp([‘Directory "’, directoryPath, ‘" does not exist.’]);
end
% All images
imds = imageDatastore( …
‘training_images’, …
‘IncludeSubfolders’, …
true …
);
% Define class names and their corresponding IDs
classNames = ["Lesion","Background"];
labelIDs =[255,0];
% Create a pixelLabelDatastore holding the ground truth pixel labels
pxds=pixelLabelDatastore( …
‘training_images’, …
classNames, …
labelIDs …
);
% Create a pixel label image datastore of all images
pximds=pixelLabelImageDatastore(imds,pxds);
% Number of Images
total_num_images=length(pximds.Images);
% Visualize random images
perm=randperm(total_num_images,4);
figure;
% Visualize the images with Mask
for idx = 1:length(perm)
% Read the image from imds
image = readimage(imds, perm(idx));
% Read the corresponding mask from pxds
mask = readimage(pxds, perm(idx));
% Display the image
subplot(2,2,idx);
imshow(image);
hold on;
binaryMask = mask(:,:,1) == classNames(1);
% Visualize boundaries on the binary mask
visboundaries(binaryMask, ‘Color’, ‘r’);
% Extract the filename for the title from imds
[~, filename] = fileparts(imds.Files{perm(idx)});
title(sprintf(‘%s’, filename), ‘Interpreter’, "none");
end
% Desired Image Size
imageSize=[224 224 3];
% Create a pixel label image datastore of all resized images
% Specify directories for resized images and labels
resizedImagesDir = ‘training_images/images-segmantation/resized/images’;
resizedLabelsDir = ‘training_images/images-segmantation/resized/labels’;
% Ensure the directories exist
if ~exist(resizedImagesDir, ‘dir’), mkdir(resizedImagesDir); end
if ~exist(resizedLabelsDir, ‘dir’), mkdir(resizedLabelsDir); end
% Resize and save images
for i = 1:length(imds.Files)
img = imread(imds.Files{i});
resizedImg = imresize(img, ‘OutputSize’, imageSize(1:2));
[~, fileName, ext] = fileparts(imds.Files{i});
imwrite(resizedImg, fullfile(resizedImagesDir, [fileName, ext]));
end
% Resize and save labels
for i = 1:length(pxds.Files)
label = imread(pxds.Files{i});
resizedLabel = imresize(label, ‘OutputSize’, imageSize(1:2), ‘Method’, ‘nearest’);
[~, fileName, ext] = fileparts(pxds.Files{i});
imwrite(resizedLabel, fullfile(resizedLabelsDir, [fileName, ext]));
end
% Create new ImageDatastore and PixelLabelDatastore from the resized data
imdsResized = imageDatastore(resizedImagesDir);
pximdsResz = pixelLabelDatastore(resizedLabelsDir, classNames, labelIDs);
% Clear all variables except the necessary variables
% clearvars -except pximdsResz classNames total_num_images imageSize
% Split the dataset into training, validation, and testing sets
numImages = numel(imdsResized.Files);
% Adjust the number as needed
testIdx = randperm(numImages, 5);
trainValidIdx = setdiff(1:numImages, testIdx);
% Adjust the number as needed
validIdx = trainValidIdx(randperm(length(trainValidIdx), 10));
trainIdx = trainValidIdx;
% Create datastores for training, validation, and testing sets
imdsTrain = subset(imdsResized, trainIdx);
imdsValid = subset(imdsResized, validIdx);
imdsTest = subset(imdsResized, testIdx);
pximdsTrain = subset(pximdsResz, trainIdx);
pximdsValid = subset(pximdsResz, validIdx);
pximdsTest = subset(pximdsResz, testIdx);
% Combine the validation image datastore with the pixel label datastore
% ValidationData expects a cell array with these combined datastores
validDS = combine(imdsValid, pximdsValid);
% As of MATLAB R2021a, this might not be necessary, and you can directly use validDS
validationData = {validDS};
% Applying the corrected transformation
trainDSConverted = transform(pximdsTrain, @(c) categoricalToNumeric(c{1}, classNames));
validDSConverted = transform(pximdsValid, @(c) categoricalToNumeric(c{1}, classNames));
% trainDSConverted2 = transform(trainDS, @(data) transformData(data));
% validDSConverted2 = transform(validDS, @(data) transformData(data));
% trainDSConverted3 = transform(trainDS, @transformData2);
% validDSConverted3 = transform(validDS, @transformData2);
% For imageDatastore
imdsTrain = subset(imdsResized, trainIdx);
imdsValid = subset(imdsResized, validIdx);
imdsTest = subset(imdsResized, testIdx);
% For pixelLabelDatastore
pxdsTrain = subset(pximdsResz, trainIdx);
pxdsValid = subset(pximdsResz, validIdx);
pxdsTest = subset(pximdsResz, testIdx);
pximdsTrain = pixelLabelImageDatastore(imdsTrain, pxdsTrain);
pximdsValid = pixelLabelImageDatastore(imdsValid, pxdsValid);
% Specify network architecture
numClasses = numel(classNames);
% Adjust based on your actual image size
imageSize = [224 224 3];
% Example using ResNet-18 backbone
lgraph = deeplabv3plusLayers(imageSize, numClasses, ‘resnet50’);
% Define the parameters for the network
options = trainingOptions(‘sgdm’, …
‘InitialLearnRate’, 0.03, …
‘Momentum’, 0.9, …
‘L2Regularization’, 0.0005, …
‘MaxEpochs’, 20, …
‘MiniBatchSize’, 32, …
‘VerboseFrequency’, 20, …
‘LearnRateSchedule’, ‘piecewise’, …
‘ExecutionEnvironment’, ‘cpu’, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, validDSConverted, … % Correct specification of ValidationData
‘ValidationFrequency’, 50, …
‘ValidationPatience’, 4, …
‘Plots’, ‘training-progress’, …
‘GradientThresholdMethod’, ‘l2norm’, …
‘GradientThreshold’, 0.05);
% Train the network
net = trainNetwork(trainDSConverted, lgraph, options);
% Semantic segmentation of test dataset based on the trained network
[pxdspredicted]=semanticseg(pximdsTest,net,’WriteLocation’,tempdir);
% Evaluation
metrics=evaluateSemanticSegmentation(pxdspredicted,pximdsTest);
% Normalized Confusion Matrix
normConfMatData = metrics.NormalizedConfusionMatrix.Variables;
figure
h=heatmap(classNames,classNames,100*normConfMatData);
h.XLabel=’Predicted Class’;
h.YLabel=’True Class’;
h.Title=’Normalized Confusion Matrix (%)’;
% Number of Images
num_test_images=length(pximdsTest.Images);
% Pick any random 2 images
perm=randperm(num_test_images,2);
% Visualize the images with Mask
for idx=1:length(perm)
% Extract filename for the title
[~,filename]=fileparts(pximdsTest.Images{idx});
% Read the original file and resize it for network purposes
I = imread(pximdsTest.Images{perm(idx)});
I = imresize(I,[imageSize(1) imageSize(2)],’bilinear’);
figure;
image(I);
hold on;
% Read the actual mask and resize it for visualization
actual_mask=imread(pximdsTest.PixelLabelData{perm(idx)});
actual_mask=imresize(actual_mask,[imageSize(1) imageSize(2)],’bilinear’);
% Ground Truth
visboundaries(actual_mask,’Color’,’r’);
% Predicted by the Algorithm
predicted_image=(uint8(readimage(pxdspredicted,perm(idx)))); % Values are 1 and 2
predicted_results=uint8(~(predicted_image-1)); % Conversion to binary and reverse the polarity to match with the labelIds
visboundaries(predicted_results,’Color’,’g’);
title(sprintf(‘%s Red- Actual, Green – Predicted’,filename),’Interpreter’,"none");
imwrite(mat2gray(predicted_results),sprintf(‘%s.png’,filename));
end
% Corrected transformation function
function outImg = categoricalToNumeric(inCategorical, classNames)
outImg = zeros(size(inCategorical,1), size(inCategorical,2), ‘uint8’);
for k = 1:length(classNames)
outImg(inCategorical == classNames{k}) = k-1;
end
end
function [img, label] = transformData(data)
% Assumes data is a cell with {image, label} format
img = data{1}; % Image data
inCategorical = data{2}; % Categorical label data
classNames = ["Lesion","Background"]; % Class names as used previously
outImg = zeros(size(inCategorical,1), size(inCategorical,2), ‘uint8’);
for k = 1:length(classNames)
outImg(inCategorical == classNames(k)) = k-1;
end
label = outImg; % Numeric label data
end
function dataOut = transformData2(dataIn)
img = dataIn{1}; % Assuming dataIn{1} is the image
label = dataIn{2}; % Assuming dataIn{2} is the label in numeric format
% Your conversion logic here, ending with…
labelCategorical = categorical(label, 0:max(label(:)), {‘Background’, ‘Lesion’});
dataOut = {img, labelCategorical};
end
When I run it, I get an error at this part:
% Define the parameters for the network
options = trainingOptions(‘sgdm’, …
‘InitialLearnRate’, 0.03, …
‘Momentum’, 0.9, …
‘L2Regularization’, 0.0005, …
‘MaxEpochs’, 20, …
‘MiniBatchSize’, 32, …
‘VerboseFrequency’, 20, …
‘LearnRateSchedule’, ‘piecewise’, …
‘ExecutionEnvironment’, ‘cpu’, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, validDSConverted, … % Correct specification of ValidationData
‘ValidationFrequency’, 50, …
‘ValidationPatience’, 4, …
‘Plots’, ‘training-progress’, …
‘GradientThresholdMethod’, ‘l2norm’, …
‘GradientThreshold’, 0.05);
Error using nnet.cnn.TrainingOptionsMiniBatch
The value of ‘ValidationData’ is invalid. Invalid transform function defined on datastore.
Error in nnet.cnn.TrainingOptionsSGDM (line 128)
this = this@nnet.cnn.TrainingOptionsMiniBatch(args.Definition,varargin{:});
Error in trainingOptions (line 440)
opts = nnet.cnn.TrainingOptionsSGDM(varargin{:});
Caused by:
Attempt to grow array along ambiguous dimension.I am tryeing to train neural network training images.
My code is based on this article: https://blogs.mathworks.com/deep-learning/2021/05/10/semantic-segmentation-for-medical-imaging/#respond
Here is complete code of my script:
% Clear workspace
clear; close all; clc;
% Specify the directory path you want to delete
directoryPath = ‘training_images/resized’;
% Check if the directory exists before trying to delete it
if exist(directoryPath, ‘dir’)
% Remove the directory and its contents
[status, message, messageId] = rmdir(directoryPath, ‘s’);
% Check if the operation was successful
if status
disp([‘Directory "’, directoryPath, ‘" has been deleted successfully.’]);
else
disp([‘Failed to delete "’, directoryPath, ‘": ‘, message]);
end
else
disp([‘Directory "’, directoryPath, ‘" does not exist.’]);
end
% All images
imds = imageDatastore( …
‘training_images’, …
‘IncludeSubfolders’, …
true …
);
% Define class names and their corresponding IDs
classNames = ["Lesion","Background"];
labelIDs =[255,0];
% Create a pixelLabelDatastore holding the ground truth pixel labels
pxds=pixelLabelDatastore( …
‘training_images’, …
classNames, …
labelIDs …
);
% Create a pixel label image datastore of all images
pximds=pixelLabelImageDatastore(imds,pxds);
% Number of Images
total_num_images=length(pximds.Images);
% Visualize random images
perm=randperm(total_num_images,4);
figure;
% Visualize the images with Mask
for idx = 1:length(perm)
% Read the image from imds
image = readimage(imds, perm(idx));
% Read the corresponding mask from pxds
mask = readimage(pxds, perm(idx));
% Display the image
subplot(2,2,idx);
imshow(image);
hold on;
binaryMask = mask(:,:,1) == classNames(1);
% Visualize boundaries on the binary mask
visboundaries(binaryMask, ‘Color’, ‘r’);
% Extract the filename for the title from imds
[~, filename] = fileparts(imds.Files{perm(idx)});
title(sprintf(‘%s’, filename), ‘Interpreter’, "none");
end
% Desired Image Size
imageSize=[224 224 3];
% Create a pixel label image datastore of all resized images
% Specify directories for resized images and labels
resizedImagesDir = ‘training_images/images-segmantation/resized/images’;
resizedLabelsDir = ‘training_images/images-segmantation/resized/labels’;
% Ensure the directories exist
if ~exist(resizedImagesDir, ‘dir’), mkdir(resizedImagesDir); end
if ~exist(resizedLabelsDir, ‘dir’), mkdir(resizedLabelsDir); end
% Resize and save images
for i = 1:length(imds.Files)
img = imread(imds.Files{i});
resizedImg = imresize(img, ‘OutputSize’, imageSize(1:2));
[~, fileName, ext] = fileparts(imds.Files{i});
imwrite(resizedImg, fullfile(resizedImagesDir, [fileName, ext]));
end
% Resize and save labels
for i = 1:length(pxds.Files)
label = imread(pxds.Files{i});
resizedLabel = imresize(label, ‘OutputSize’, imageSize(1:2), ‘Method’, ‘nearest’);
[~, fileName, ext] = fileparts(pxds.Files{i});
imwrite(resizedLabel, fullfile(resizedLabelsDir, [fileName, ext]));
end
% Create new ImageDatastore and PixelLabelDatastore from the resized data
imdsResized = imageDatastore(resizedImagesDir);
pximdsResz = pixelLabelDatastore(resizedLabelsDir, classNames, labelIDs);
% Clear all variables except the necessary variables
% clearvars -except pximdsResz classNames total_num_images imageSize
% Split the dataset into training, validation, and testing sets
numImages = numel(imdsResized.Files);
% Adjust the number as needed
testIdx = randperm(numImages, 5);
trainValidIdx = setdiff(1:numImages, testIdx);
% Adjust the number as needed
validIdx = trainValidIdx(randperm(length(trainValidIdx), 10));
trainIdx = trainValidIdx;
% Create datastores for training, validation, and testing sets
imdsTrain = subset(imdsResized, trainIdx);
imdsValid = subset(imdsResized, validIdx);
imdsTest = subset(imdsResized, testIdx);
pximdsTrain = subset(pximdsResz, trainIdx);
pximdsValid = subset(pximdsResz, validIdx);
pximdsTest = subset(pximdsResz, testIdx);
% Combine the validation image datastore with the pixel label datastore
% ValidationData expects a cell array with these combined datastores
validDS = combine(imdsValid, pximdsValid);
% As of MATLAB R2021a, this might not be necessary, and you can directly use validDS
validationData = {validDS};
% Applying the corrected transformation
trainDSConverted = transform(pximdsTrain, @(c) categoricalToNumeric(c{1}, classNames));
validDSConverted = transform(pximdsValid, @(c) categoricalToNumeric(c{1}, classNames));
% trainDSConverted2 = transform(trainDS, @(data) transformData(data));
% validDSConverted2 = transform(validDS, @(data) transformData(data));
% trainDSConverted3 = transform(trainDS, @transformData2);
% validDSConverted3 = transform(validDS, @transformData2);
% For imageDatastore
imdsTrain = subset(imdsResized, trainIdx);
imdsValid = subset(imdsResized, validIdx);
imdsTest = subset(imdsResized, testIdx);
% For pixelLabelDatastore
pxdsTrain = subset(pximdsResz, trainIdx);
pxdsValid = subset(pximdsResz, validIdx);
pxdsTest = subset(pximdsResz, testIdx);
pximdsTrain = pixelLabelImageDatastore(imdsTrain, pxdsTrain);
pximdsValid = pixelLabelImageDatastore(imdsValid, pxdsValid);
% Specify network architecture
numClasses = numel(classNames);
% Adjust based on your actual image size
imageSize = [224 224 3];
% Example using ResNet-18 backbone
lgraph = deeplabv3plusLayers(imageSize, numClasses, ‘resnet50’);
% Define the parameters for the network
options = trainingOptions(‘sgdm’, …
‘InitialLearnRate’, 0.03, …
‘Momentum’, 0.9, …
‘L2Regularization’, 0.0005, …
‘MaxEpochs’, 20, …
‘MiniBatchSize’, 32, …
‘VerboseFrequency’, 20, …
‘LearnRateSchedule’, ‘piecewise’, …
‘ExecutionEnvironment’, ‘cpu’, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, validDSConverted, … % Correct specification of ValidationData
‘ValidationFrequency’, 50, …
‘ValidationPatience’, 4, …
‘Plots’, ‘training-progress’, …
‘GradientThresholdMethod’, ‘l2norm’, …
‘GradientThreshold’, 0.05);
% Train the network
net = trainNetwork(trainDSConverted, lgraph, options);
% Semantic segmentation of test dataset based on the trained network
[pxdspredicted]=semanticseg(pximdsTest,net,’WriteLocation’,tempdir);
% Evaluation
metrics=evaluateSemanticSegmentation(pxdspredicted,pximdsTest);
% Normalized Confusion Matrix
normConfMatData = metrics.NormalizedConfusionMatrix.Variables;
figure
h=heatmap(classNames,classNames,100*normConfMatData);
h.XLabel=’Predicted Class’;
h.YLabel=’True Class’;
h.Title=’Normalized Confusion Matrix (%)’;
% Number of Images
num_test_images=length(pximdsTest.Images);
% Pick any random 2 images
perm=randperm(num_test_images,2);
% Visualize the images with Mask
for idx=1:length(perm)
% Extract filename for the title
[~,filename]=fileparts(pximdsTest.Images{idx});
% Read the original file and resize it for network purposes
I = imread(pximdsTest.Images{perm(idx)});
I = imresize(I,[imageSize(1) imageSize(2)],’bilinear’);
figure;
image(I);
hold on;
% Read the actual mask and resize it for visualization
actual_mask=imread(pximdsTest.PixelLabelData{perm(idx)});
actual_mask=imresize(actual_mask,[imageSize(1) imageSize(2)],’bilinear’);
% Ground Truth
visboundaries(actual_mask,’Color’,’r’);
% Predicted by the Algorithm
predicted_image=(uint8(readimage(pxdspredicted,perm(idx)))); % Values are 1 and 2
predicted_results=uint8(~(predicted_image-1)); % Conversion to binary and reverse the polarity to match with the labelIds
visboundaries(predicted_results,’Color’,’g’);
title(sprintf(‘%s Red- Actual, Green – Predicted’,filename),’Interpreter’,"none");
imwrite(mat2gray(predicted_results),sprintf(‘%s.png’,filename));
end
% Corrected transformation function
function outImg = categoricalToNumeric(inCategorical, classNames)
outImg = zeros(size(inCategorical,1), size(inCategorical,2), ‘uint8’);
for k = 1:length(classNames)
outImg(inCategorical == classNames{k}) = k-1;
end
end
function [img, label] = transformData(data)
% Assumes data is a cell with {image, label} format
img = data{1}; % Image data
inCategorical = data{2}; % Categorical label data
classNames = ["Lesion","Background"]; % Class names as used previously
outImg = zeros(size(inCategorical,1), size(inCategorical,2), ‘uint8’);
for k = 1:length(classNames)
outImg(inCategorical == classNames(k)) = k-1;
end
label = outImg; % Numeric label data
end
function dataOut = transformData2(dataIn)
img = dataIn{1}; % Assuming dataIn{1} is the image
label = dataIn{2}; % Assuming dataIn{2} is the label in numeric format
% Your conversion logic here, ending with…
labelCategorical = categorical(label, 0:max(label(:)), {‘Background’, ‘Lesion’});
dataOut = {img, labelCategorical};
end
When I run it, I get an error at this part:
% Define the parameters for the network
options = trainingOptions(‘sgdm’, …
‘InitialLearnRate’, 0.03, …
‘Momentum’, 0.9, …
‘L2Regularization’, 0.0005, …
‘MaxEpochs’, 20, …
‘MiniBatchSize’, 32, …
‘VerboseFrequency’, 20, …
‘LearnRateSchedule’, ‘piecewise’, …
‘ExecutionEnvironment’, ‘cpu’, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, validDSConverted, … % Correct specification of ValidationData
‘ValidationFrequency’, 50, …
‘ValidationPatience’, 4, …
‘Plots’, ‘training-progress’, …
‘GradientThresholdMethod’, ‘l2norm’, …
‘GradientThreshold’, 0.05);
Error using nnet.cnn.TrainingOptionsMiniBatch
The value of ‘ValidationData’ is invalid. Invalid transform function defined on datastore.
Error in nnet.cnn.TrainingOptionsSGDM (line 128)
this = this@nnet.cnn.TrainingOptionsMiniBatch(args.Definition,varargin{:});
Error in trainingOptions (line 440)
opts = nnet.cnn.TrainingOptionsSGDM(varargin{:});
Caused by:
Attempt to grow array along ambiguous dimension. I am tryeing to train neural network training images.
My code is based on this article: https://blogs.mathworks.com/deep-learning/2021/05/10/semantic-segmentation-for-medical-imaging/#respond
Here is complete code of my script:
% Clear workspace
clear; close all; clc;
% Specify the directory path you want to delete
directoryPath = ‘training_images/resized’;
% Check if the directory exists before trying to delete it
if exist(directoryPath, ‘dir’)
% Remove the directory and its contents
[status, message, messageId] = rmdir(directoryPath, ‘s’);
% Check if the operation was successful
if status
disp([‘Directory "’, directoryPath, ‘" has been deleted successfully.’]);
else
disp([‘Failed to delete "’, directoryPath, ‘": ‘, message]);
end
else
disp([‘Directory "’, directoryPath, ‘" does not exist.’]);
end
% All images
imds = imageDatastore( …
‘training_images’, …
‘IncludeSubfolders’, …
true …
);
% Define class names and their corresponding IDs
classNames = ["Lesion","Background"];
labelIDs =[255,0];
% Create a pixelLabelDatastore holding the ground truth pixel labels
pxds=pixelLabelDatastore( …
‘training_images’, …
classNames, …
labelIDs …
);
% Create a pixel label image datastore of all images
pximds=pixelLabelImageDatastore(imds,pxds);
% Number of Images
total_num_images=length(pximds.Images);
% Visualize random images
perm=randperm(total_num_images,4);
figure;
% Visualize the images with Mask
for idx = 1:length(perm)
% Read the image from imds
image = readimage(imds, perm(idx));
% Read the corresponding mask from pxds
mask = readimage(pxds, perm(idx));
% Display the image
subplot(2,2,idx);
imshow(image);
hold on;
binaryMask = mask(:,:,1) == classNames(1);
% Visualize boundaries on the binary mask
visboundaries(binaryMask, ‘Color’, ‘r’);
% Extract the filename for the title from imds
[~, filename] = fileparts(imds.Files{perm(idx)});
title(sprintf(‘%s’, filename), ‘Interpreter’, "none");
end
% Desired Image Size
imageSize=[224 224 3];
% Create a pixel label image datastore of all resized images
% Specify directories for resized images and labels
resizedImagesDir = ‘training_images/images-segmantation/resized/images’;
resizedLabelsDir = ‘training_images/images-segmantation/resized/labels’;
% Ensure the directories exist
if ~exist(resizedImagesDir, ‘dir’), mkdir(resizedImagesDir); end
if ~exist(resizedLabelsDir, ‘dir’), mkdir(resizedLabelsDir); end
% Resize and save images
for i = 1:length(imds.Files)
img = imread(imds.Files{i});
resizedImg = imresize(img, ‘OutputSize’, imageSize(1:2));
[~, fileName, ext] = fileparts(imds.Files{i});
imwrite(resizedImg, fullfile(resizedImagesDir, [fileName, ext]));
end
% Resize and save labels
for i = 1:length(pxds.Files)
label = imread(pxds.Files{i});
resizedLabel = imresize(label, ‘OutputSize’, imageSize(1:2), ‘Method’, ‘nearest’);
[~, fileName, ext] = fileparts(pxds.Files{i});
imwrite(resizedLabel, fullfile(resizedLabelsDir, [fileName, ext]));
end
% Create new ImageDatastore and PixelLabelDatastore from the resized data
imdsResized = imageDatastore(resizedImagesDir);
pximdsResz = pixelLabelDatastore(resizedLabelsDir, classNames, labelIDs);
% Clear all variables except the necessary variables
% clearvars -except pximdsResz classNames total_num_images imageSize
% Split the dataset into training, validation, and testing sets
numImages = numel(imdsResized.Files);
% Adjust the number as needed
testIdx = randperm(numImages, 5);
trainValidIdx = setdiff(1:numImages, testIdx);
% Adjust the number as needed
validIdx = trainValidIdx(randperm(length(trainValidIdx), 10));
trainIdx = trainValidIdx;
% Create datastores for training, validation, and testing sets
imdsTrain = subset(imdsResized, trainIdx);
imdsValid = subset(imdsResized, validIdx);
imdsTest = subset(imdsResized, testIdx);
pximdsTrain = subset(pximdsResz, trainIdx);
pximdsValid = subset(pximdsResz, validIdx);
pximdsTest = subset(pximdsResz, testIdx);
% Combine the validation image datastore with the pixel label datastore
% ValidationData expects a cell array with these combined datastores
validDS = combine(imdsValid, pximdsValid);
% As of MATLAB R2021a, this might not be necessary, and you can directly use validDS
validationData = {validDS};
% Applying the corrected transformation
trainDSConverted = transform(pximdsTrain, @(c) categoricalToNumeric(c{1}, classNames));
validDSConverted = transform(pximdsValid, @(c) categoricalToNumeric(c{1}, classNames));
% trainDSConverted2 = transform(trainDS, @(data) transformData(data));
% validDSConverted2 = transform(validDS, @(data) transformData(data));
% trainDSConverted3 = transform(trainDS, @transformData2);
% validDSConverted3 = transform(validDS, @transformData2);
% For imageDatastore
imdsTrain = subset(imdsResized, trainIdx);
imdsValid = subset(imdsResized, validIdx);
imdsTest = subset(imdsResized, testIdx);
% For pixelLabelDatastore
pxdsTrain = subset(pximdsResz, trainIdx);
pxdsValid = subset(pximdsResz, validIdx);
pxdsTest = subset(pximdsResz, testIdx);
pximdsTrain = pixelLabelImageDatastore(imdsTrain, pxdsTrain);
pximdsValid = pixelLabelImageDatastore(imdsValid, pxdsValid);
% Specify network architecture
numClasses = numel(classNames);
% Adjust based on your actual image size
imageSize = [224 224 3];
% Example using ResNet-18 backbone
lgraph = deeplabv3plusLayers(imageSize, numClasses, ‘resnet50’);
% Define the parameters for the network
options = trainingOptions(‘sgdm’, …
‘InitialLearnRate’, 0.03, …
‘Momentum’, 0.9, …
‘L2Regularization’, 0.0005, …
‘MaxEpochs’, 20, …
‘MiniBatchSize’, 32, …
‘VerboseFrequency’, 20, …
‘LearnRateSchedule’, ‘piecewise’, …
‘ExecutionEnvironment’, ‘cpu’, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, validDSConverted, … % Correct specification of ValidationData
‘ValidationFrequency’, 50, …
‘ValidationPatience’, 4, …
‘Plots’, ‘training-progress’, …
‘GradientThresholdMethod’, ‘l2norm’, …
‘GradientThreshold’, 0.05);
% Train the network
net = trainNetwork(trainDSConverted, lgraph, options);
% Semantic segmentation of test dataset based on the trained network
[pxdspredicted]=semanticseg(pximdsTest,net,’WriteLocation’,tempdir);
% Evaluation
metrics=evaluateSemanticSegmentation(pxdspredicted,pximdsTest);
% Normalized Confusion Matrix
normConfMatData = metrics.NormalizedConfusionMatrix.Variables;
figure
h=heatmap(classNames,classNames,100*normConfMatData);
h.XLabel=’Predicted Class’;
h.YLabel=’True Class’;
h.Title=’Normalized Confusion Matrix (%)’;
% Number of Images
num_test_images=length(pximdsTest.Images);
% Pick any random 2 images
perm=randperm(num_test_images,2);
% Visualize the images with Mask
for idx=1:length(perm)
% Extract filename for the title
[~,filename]=fileparts(pximdsTest.Images{idx});
% Read the original file and resize it for network purposes
I = imread(pximdsTest.Images{perm(idx)});
I = imresize(I,[imageSize(1) imageSize(2)],’bilinear’);
figure;
image(I);
hold on;
% Read the actual mask and resize it for visualization
actual_mask=imread(pximdsTest.PixelLabelData{perm(idx)});
actual_mask=imresize(actual_mask,[imageSize(1) imageSize(2)],’bilinear’);
% Ground Truth
visboundaries(actual_mask,’Color’,’r’);
% Predicted by the Algorithm
predicted_image=(uint8(readimage(pxdspredicted,perm(idx)))); % Values are 1 and 2
predicted_results=uint8(~(predicted_image-1)); % Conversion to binary and reverse the polarity to match with the labelIds
visboundaries(predicted_results,’Color’,’g’);
title(sprintf(‘%s Red- Actual, Green – Predicted’,filename),’Interpreter’,"none");
imwrite(mat2gray(predicted_results),sprintf(‘%s.png’,filename));
end
% Corrected transformation function
function outImg = categoricalToNumeric(inCategorical, classNames)
outImg = zeros(size(inCategorical,1), size(inCategorical,2), ‘uint8’);
for k = 1:length(classNames)
outImg(inCategorical == classNames{k}) = k-1;
end
end
function [img, label] = transformData(data)
% Assumes data is a cell with {image, label} format
img = data{1}; % Image data
inCategorical = data{2}; % Categorical label data
classNames = ["Lesion","Background"]; % Class names as used previously
outImg = zeros(size(inCategorical,1), size(inCategorical,2), ‘uint8’);
for k = 1:length(classNames)
outImg(inCategorical == classNames(k)) = k-1;
end
label = outImg; % Numeric label data
end
function dataOut = transformData2(dataIn)
img = dataIn{1}; % Assuming dataIn{1} is the image
label = dataIn{2}; % Assuming dataIn{2} is the label in numeric format
% Your conversion logic here, ending with…
labelCategorical = categorical(label, 0:max(label(:)), {‘Background’, ‘Lesion’});
dataOut = {img, labelCategorical};
end
When I run it, I get an error at this part:
% Define the parameters for the network
options = trainingOptions(‘sgdm’, …
‘InitialLearnRate’, 0.03, …
‘Momentum’, 0.9, …
‘L2Regularization’, 0.0005, …
‘MaxEpochs’, 20, …
‘MiniBatchSize’, 32, …
‘VerboseFrequency’, 20, …
‘LearnRateSchedule’, ‘piecewise’, …
‘ExecutionEnvironment’, ‘cpu’, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, validDSConverted, … % Correct specification of ValidationData
‘ValidationFrequency’, 50, …
‘ValidationPatience’, 4, …
‘Plots’, ‘training-progress’, …
‘GradientThresholdMethod’, ‘l2norm’, …
‘GradientThreshold’, 0.05);
Error using nnet.cnn.TrainingOptionsMiniBatch
The value of ‘ValidationData’ is invalid. Invalid transform function defined on datastore.
Error in nnet.cnn.TrainingOptionsSGDM (line 128)
this = this@nnet.cnn.TrainingOptionsMiniBatch(args.Definition,varargin{:});
Error in trainingOptions (line 440)
opts = nnet.cnn.TrainingOptionsSGDM(varargin{:});
Caused by:
Attempt to grow array along ambiguous dimension. trainnetwork, trainingoptions MATLAB Answers — New Questions
How to use parsim with a Simulink model containing an FMU with dependencies? Model works with sim.
Hi,
We have a Simulink model that solves well using the sim command and the Simulink UI "Run" button. The FMU launches a solver process and two talk to each other over ZeroMQ and this works well for one instance. The port that the solver binds to is determined at run time based on the available ports and theoretically this approach should work when multiple simulations are launched in parallel, since no common resources are used or shared. The FMU also needs a few DLLs that are loaded at run time. These are currently placed in the same folder as the Simulink model and runner script.
We have installed the Parallel Computing Toolbox and can run the base example provided. However, when we try to programmatically run our simulations using parsim, it gets stuck on the "loading the model" stage for a long time. We developed our parsim implementation by extending the base example in docs and use setVariable() to assign value to individual simulations. We are also just wanting to parallelize in the "local" context on a 8 core CPU Windows x64 machine. We were wondering, to make sure that the dependencies are correctly getting copied to the individual workers:
Is it possible to view/inspect these temporary directories used by the worker processes? Where are they typically located? I did not find them in the slprj folder.
How can we control which dependencies are copied where? While we do not, for our case, need specific dependencies on specific workers, this maybe needed at times.
Is there a general rule of thumb around how big the FMU should be or the number or size of dependencies or workspace data should be for parsim workers to "work well"?
Also, could we get clarification on the following line in this answer post:
"The ‘parsim’ function was employed to simulate multiple models specified in the ‘SimulationInput’ object concurrently. While ‘parsim’ can effectively reduce the simulation time, it is crucial to structure the model appropriately. Specifically, the simulation should not rely on the results of previous steps. In other words, there should be no dependency between the simulations of the model at different time steps."
Does this mean that in parsim, the model does not keep track of the model state between timesteps? So does this mean we can only solve for one timestep at a time and then relaunch the sim?Hi,
We have a Simulink model that solves well using the sim command and the Simulink UI "Run" button. The FMU launches a solver process and two talk to each other over ZeroMQ and this works well for one instance. The port that the solver binds to is determined at run time based on the available ports and theoretically this approach should work when multiple simulations are launched in parallel, since no common resources are used or shared. The FMU also needs a few DLLs that are loaded at run time. These are currently placed in the same folder as the Simulink model and runner script.
We have installed the Parallel Computing Toolbox and can run the base example provided. However, when we try to programmatically run our simulations using parsim, it gets stuck on the "loading the model" stage for a long time. We developed our parsim implementation by extending the base example in docs and use setVariable() to assign value to individual simulations. We are also just wanting to parallelize in the "local" context on a 8 core CPU Windows x64 machine. We were wondering, to make sure that the dependencies are correctly getting copied to the individual workers:
Is it possible to view/inspect these temporary directories used by the worker processes? Where are they typically located? I did not find them in the slprj folder.
How can we control which dependencies are copied where? While we do not, for our case, need specific dependencies on specific workers, this maybe needed at times.
Is there a general rule of thumb around how big the FMU should be or the number or size of dependencies or workspace data should be for parsim workers to "work well"?
Also, could we get clarification on the following line in this answer post:
"The ‘parsim’ function was employed to simulate multiple models specified in the ‘SimulationInput’ object concurrently. While ‘parsim’ can effectively reduce the simulation time, it is crucial to structure the model appropriately. Specifically, the simulation should not rely on the results of previous steps. In other words, there should be no dependency between the simulations of the model at different time steps."
Does this mean that in parsim, the model does not keep track of the model state between timesteps? So does this mean we can only solve for one timestep at a time and then relaunch the sim? Hi,
We have a Simulink model that solves well using the sim command and the Simulink UI "Run" button. The FMU launches a solver process and two talk to each other over ZeroMQ and this works well for one instance. The port that the solver binds to is determined at run time based on the available ports and theoretically this approach should work when multiple simulations are launched in parallel, since no common resources are used or shared. The FMU also needs a few DLLs that are loaded at run time. These are currently placed in the same folder as the Simulink model and runner script.
We have installed the Parallel Computing Toolbox and can run the base example provided. However, when we try to programmatically run our simulations using parsim, it gets stuck on the "loading the model" stage for a long time. We developed our parsim implementation by extending the base example in docs and use setVariable() to assign value to individual simulations. We are also just wanting to parallelize in the "local" context on a 8 core CPU Windows x64 machine. We were wondering, to make sure that the dependencies are correctly getting copied to the individual workers:
Is it possible to view/inspect these temporary directories used by the worker processes? Where are they typically located? I did not find them in the slprj folder.
How can we control which dependencies are copied where? While we do not, for our case, need specific dependencies on specific workers, this maybe needed at times.
Is there a general rule of thumb around how big the FMU should be or the number or size of dependencies or workspace data should be for parsim workers to "work well"?
Also, could we get clarification on the following line in this answer post:
"The ‘parsim’ function was employed to simulate multiple models specified in the ‘SimulationInput’ object concurrently. While ‘parsim’ can effectively reduce the simulation time, it is crucial to structure the model appropriately. Specifically, the simulation should not rely on the results of previous steps. In other words, there should be no dependency between the simulations of the model at different time steps."
Does this mean that in parsim, the model does not keep track of the model state between timesteps? So does this mean we can only solve for one timestep at a time and then relaunch the sim? parsim, fmu MATLAB Answers — New Questions
when connecting to Raspberry Pi 4-B board: Error executing command “make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile”.
Hello,
I am trying to connect to a Raspberry Pi 4-B with "MATLAB Support Package for Raspberry Pi Hardware". I have selected "Costomized the existing Rasbian OS running on my hardware". I wrote this code after the installation was complete: r = raspi(‘192.168.0.99′,’pi’,’raspberry’) where 192.168.0.99 is the IP of the board connecting via WIFI. After a while, I encountered this error: Error executing command "make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile".
Can you help me what to do?
The complete response of the MATLAB in command window is as follows:
myrasp = raspi(‘192.168.0.99′,’pi’,’raspberry’)
### Updating Raspberry Pi I/O server…
### Connecting to board…
### Connected to 192.168.0.99…
### Installing userland software (this might take a while)…
### Installing nanomsg Library (this might take a while)…
### Creating server folder…
### Transferring source files…
### Building MATLAB I/O server…
Error executing command "make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile". Details:
STDERR: IO_wrapperv4l2.c: In function ‘v4l2CameraSettings’:
IO_wrapperv4l2.c:133:14: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka ‘char
*’} differ in signedness [-Wpointer-sign]
133 | jsonData = &payloadBufferRx[index];
| ^
IO_wrapperCameraboard.c: In function ‘camerboardInitialize’:
IO_wrapperCameraboard.c:38:19: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka
‘char *’} differ in signedness [-Wpointer-sign]
38 | controlParams = &payloadBufferRx[index];
| ^
IO_wrapperCameraboard.c:41:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
41 | printf("REQUEST_CAMERABOARD_INIT: (w, h, fps, q) = [%d, %d, %d, %d]n", width, height,
| ^~~~~~
IO_wrapperCameraboard.c:41:5: warning: incompatible implicit declaration of built-in function ‘printf’
IO_wrapperCameraboard.c:11:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
10 | #include "IO_wrapperCameraboard.h"
+++ |+#include <stdio.h>
11 |
IO_wrapperCameraboard.c: In function ‘cameraboardSnapshot’:
IO_wrapperCameraboard.c:66:5: warning: incompatible implicit declaration of built-in function ‘printf’
66 | printf("REQUEST_CAMERABOARD_SNAPSHOT n");
| ^~~~~~
IO_wrapperCameraboard.c:66:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
IO_wrapperCameraboard.c: In function ‘cameraboardControl’:
IO_wrapperCameraboard.c:95:19: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka
‘char *’} differ in signedness [-Wpointer-sign]
95 | controlParams = &payloadBufferRx[0];
| ^
IO_wrapperCameraboard.c:96:5: warning: incompatible implicit declaration of built-in function ‘printf’
96 | printf("REQUEST_CAMERABOARD_CONTROL: %s n", controlParams);
| ^~~~~~
IO_wrapperCameraboard.c:96:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
IO_wrapperCameraboard.c: In function ‘cameraboardTerminate’:
IO_wrapperCameraboard.c:118:5: warning: incompatible implicit declaration of built-in function ‘printf’
118 | printf("REQUEST_CAMERABOARD_TERMINATE n");
| ^~~~~~
IO_wrapperCameraboard.c:118:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
In file included from sharedServer.h:16,
from mw_wrapperCANChannel.h:16,
from mw_wrapperCANChannel.c:11:
mw_wrapperCANChannel.c: In function ‘canWrite’:
mw_wrapperCANChannel.c:18:23: warning: too many arguments for format [-Wformat-extra-args]
18 | LOG_PRINT(stdout, "REQUEST_CAN_WRITE: n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:53:26: warning: too many arguments for format [-Wformat-extra-args]
53 | LOG_PRINT(stdout,"CANChannel: Write successful n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:56:26: warning: too many arguments for format [-Wformat-extra-args]
56 | LOG_PRINT(stdout,"CANChannel: Write failed n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c: In function ‘canRead’:
mw_wrapperCANChannel.c:65:22: warning: too many arguments for format [-Wformat-extra-args]
65 | LOG_PRINT(stdout,"REQUEST_CAN_Read: n",0);
| ^~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:98:26: warning: too many arguments for format [-Wformat-extra-args]
98 | LOG_PRINT(stdout,"CANChannel: Read successful n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:100:26: warning: too many arguments for format [-Wformat-extra-args]
100 | LOG_PRINT(stdout,"CANChannel: Read failed n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
picam.c:19:10: fatal error: RaspiCamControl.h: No such file or directory
19 | #include "RaspiCamControl.h"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:81: obj/picam.o] Error 1
STDOUT: make: Entering directory ‘/opt/MATLAB/mw_server_v22.1.0’
[Compiling] IO_wrapperv4l2.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ IO_wrapperv4l2.c
-o obj/IO_wrapperv4l2.o
[Compiling] MW_PWM.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ MW_PWM.c -o
obj/MW_PWM.o
[Compiling] MW_pigs.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ MW_pigs.c -o
obj/MW_pigs.o
[Compiling] sharedServer.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ sharedServer.c
-o obj/sharedServer.o
[Compiling] IO_wrapperCameraboard.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_
IO_wrapperCameraboard.c -o obj/IO_wrapperCameraboard.o
[Compiling] mw_wrapperCANChannel.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_
mw_wrapperCANChannel.c -o obj/mw_wrapperCANChannel.o
[Compiling] LED.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ LED.c -o
obj/LED.o
[Compiling] picam.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ picam.c -o
obj/picam.o
make: Leaving directory ‘/opt/MATLAB/mw_server_v22.1.0’Hello,
I am trying to connect to a Raspberry Pi 4-B with "MATLAB Support Package for Raspberry Pi Hardware". I have selected "Costomized the existing Rasbian OS running on my hardware". I wrote this code after the installation was complete: r = raspi(‘192.168.0.99′,’pi’,’raspberry’) where 192.168.0.99 is the IP of the board connecting via WIFI. After a while, I encountered this error: Error executing command "make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile".
Can you help me what to do?
The complete response of the MATLAB in command window is as follows:
myrasp = raspi(‘192.168.0.99′,’pi’,’raspberry’)
### Updating Raspberry Pi I/O server…
### Connecting to board…
### Connected to 192.168.0.99…
### Installing userland software (this might take a while)…
### Installing nanomsg Library (this might take a while)…
### Creating server folder…
### Transferring source files…
### Building MATLAB I/O server…
Error executing command "make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile". Details:
STDERR: IO_wrapperv4l2.c: In function ‘v4l2CameraSettings’:
IO_wrapperv4l2.c:133:14: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka ‘char
*’} differ in signedness [-Wpointer-sign]
133 | jsonData = &payloadBufferRx[index];
| ^
IO_wrapperCameraboard.c: In function ‘camerboardInitialize’:
IO_wrapperCameraboard.c:38:19: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka
‘char *’} differ in signedness [-Wpointer-sign]
38 | controlParams = &payloadBufferRx[index];
| ^
IO_wrapperCameraboard.c:41:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
41 | printf("REQUEST_CAMERABOARD_INIT: (w, h, fps, q) = [%d, %d, %d, %d]n", width, height,
| ^~~~~~
IO_wrapperCameraboard.c:41:5: warning: incompatible implicit declaration of built-in function ‘printf’
IO_wrapperCameraboard.c:11:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
10 | #include "IO_wrapperCameraboard.h"
+++ |+#include <stdio.h>
11 |
IO_wrapperCameraboard.c: In function ‘cameraboardSnapshot’:
IO_wrapperCameraboard.c:66:5: warning: incompatible implicit declaration of built-in function ‘printf’
66 | printf("REQUEST_CAMERABOARD_SNAPSHOT n");
| ^~~~~~
IO_wrapperCameraboard.c:66:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
IO_wrapperCameraboard.c: In function ‘cameraboardControl’:
IO_wrapperCameraboard.c:95:19: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka
‘char *’} differ in signedness [-Wpointer-sign]
95 | controlParams = &payloadBufferRx[0];
| ^
IO_wrapperCameraboard.c:96:5: warning: incompatible implicit declaration of built-in function ‘printf’
96 | printf("REQUEST_CAMERABOARD_CONTROL: %s n", controlParams);
| ^~~~~~
IO_wrapperCameraboard.c:96:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
IO_wrapperCameraboard.c: In function ‘cameraboardTerminate’:
IO_wrapperCameraboard.c:118:5: warning: incompatible implicit declaration of built-in function ‘printf’
118 | printf("REQUEST_CAMERABOARD_TERMINATE n");
| ^~~~~~
IO_wrapperCameraboard.c:118:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
In file included from sharedServer.h:16,
from mw_wrapperCANChannel.h:16,
from mw_wrapperCANChannel.c:11:
mw_wrapperCANChannel.c: In function ‘canWrite’:
mw_wrapperCANChannel.c:18:23: warning: too many arguments for format [-Wformat-extra-args]
18 | LOG_PRINT(stdout, "REQUEST_CAN_WRITE: n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:53:26: warning: too many arguments for format [-Wformat-extra-args]
53 | LOG_PRINT(stdout,"CANChannel: Write successful n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:56:26: warning: too many arguments for format [-Wformat-extra-args]
56 | LOG_PRINT(stdout,"CANChannel: Write failed n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c: In function ‘canRead’:
mw_wrapperCANChannel.c:65:22: warning: too many arguments for format [-Wformat-extra-args]
65 | LOG_PRINT(stdout,"REQUEST_CAN_Read: n",0);
| ^~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:98:26: warning: too many arguments for format [-Wformat-extra-args]
98 | LOG_PRINT(stdout,"CANChannel: Read successful n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:100:26: warning: too many arguments for format [-Wformat-extra-args]
100 | LOG_PRINT(stdout,"CANChannel: Read failed n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
picam.c:19:10: fatal error: RaspiCamControl.h: No such file or directory
19 | #include "RaspiCamControl.h"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:81: obj/picam.o] Error 1
STDOUT: make: Entering directory ‘/opt/MATLAB/mw_server_v22.1.0’
[Compiling] IO_wrapperv4l2.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ IO_wrapperv4l2.c
-o obj/IO_wrapperv4l2.o
[Compiling] MW_PWM.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ MW_PWM.c -o
obj/MW_PWM.o
[Compiling] MW_pigs.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ MW_pigs.c -o
obj/MW_pigs.o
[Compiling] sharedServer.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ sharedServer.c
-o obj/sharedServer.o
[Compiling] IO_wrapperCameraboard.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_
IO_wrapperCameraboard.c -o obj/IO_wrapperCameraboard.o
[Compiling] mw_wrapperCANChannel.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_
mw_wrapperCANChannel.c -o obj/mw_wrapperCANChannel.o
[Compiling] LED.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ LED.c -o
obj/LED.o
[Compiling] picam.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ picam.c -o
obj/picam.o
make: Leaving directory ‘/opt/MATLAB/mw_server_v22.1.0’ Hello,
I am trying to connect to a Raspberry Pi 4-B with "MATLAB Support Package for Raspberry Pi Hardware". I have selected "Costomized the existing Rasbian OS running on my hardware". I wrote this code after the installation was complete: r = raspi(‘192.168.0.99′,’pi’,’raspberry’) where 192.168.0.99 is the IP of the board connecting via WIFI. After a while, I encountered this error: Error executing command "make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile".
Can you help me what to do?
The complete response of the MATLAB in command window is as follows:
myrasp = raspi(‘192.168.0.99′,’pi’,’raspberry’)
### Updating Raspberry Pi I/O server…
### Connecting to board…
### Connected to 192.168.0.99…
### Installing userland software (this might take a while)…
### Installing nanomsg Library (this might take a while)…
### Creating server folder…
### Transferring source files…
### Building MATLAB I/O server…
Error executing command "make ONLY_MATLAB_IO=1 -C /opt/MATLAB/mw_server_v22.1.0 -f Makefile". Details:
STDERR: IO_wrapperv4l2.c: In function ‘v4l2CameraSettings’:
IO_wrapperv4l2.c:133:14: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka ‘char
*’} differ in signedness [-Wpointer-sign]
133 | jsonData = &payloadBufferRx[index];
| ^
IO_wrapperCameraboard.c: In function ‘camerboardInitialize’:
IO_wrapperCameraboard.c:38:19: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka
‘char *’} differ in signedness [-Wpointer-sign]
38 | controlParams = &payloadBufferRx[index];
| ^
IO_wrapperCameraboard.c:41:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
41 | printf("REQUEST_CAMERABOARD_INIT: (w, h, fps, q) = [%d, %d, %d, %d]n", width, height,
| ^~~~~~
IO_wrapperCameraboard.c:41:5: warning: incompatible implicit declaration of built-in function ‘printf’
IO_wrapperCameraboard.c:11:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
10 | #include "IO_wrapperCameraboard.h"
+++ |+#include <stdio.h>
11 |
IO_wrapperCameraboard.c: In function ‘cameraboardSnapshot’:
IO_wrapperCameraboard.c:66:5: warning: incompatible implicit declaration of built-in function ‘printf’
66 | printf("REQUEST_CAMERABOARD_SNAPSHOT n");
| ^~~~~~
IO_wrapperCameraboard.c:66:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
IO_wrapperCameraboard.c: In function ‘cameraboardControl’:
IO_wrapperCameraboard.c:95:19: warning: pointer targets in assignment from ‘uint8_T *’ {aka ‘unsigned char *’} to ‘char_T *’ {aka
‘char *’} differ in signedness [-Wpointer-sign]
95 | controlParams = &payloadBufferRx[0];
| ^
IO_wrapperCameraboard.c:96:5: warning: incompatible implicit declaration of built-in function ‘printf’
96 | printf("REQUEST_CAMERABOARD_CONTROL: %s n", controlParams);
| ^~~~~~
IO_wrapperCameraboard.c:96:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
IO_wrapperCameraboard.c: In function ‘cameraboardTerminate’:
IO_wrapperCameraboard.c:118:5: warning: incompatible implicit declaration of built-in function ‘printf’
118 | printf("REQUEST_CAMERABOARD_TERMINATE n");
| ^~~~~~
IO_wrapperCameraboard.c:118:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
In file included from sharedServer.h:16,
from mw_wrapperCANChannel.h:16,
from mw_wrapperCANChannel.c:11:
mw_wrapperCANChannel.c: In function ‘canWrite’:
mw_wrapperCANChannel.c:18:23: warning: too many arguments for format [-Wformat-extra-args]
18 | LOG_PRINT(stdout, "REQUEST_CAN_WRITE: n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:53:26: warning: too many arguments for format [-Wformat-extra-args]
53 | LOG_PRINT(stdout,"CANChannel: Write successful n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:56:26: warning: too many arguments for format [-Wformat-extra-args]
56 | LOG_PRINT(stdout,"CANChannel: Write failed n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c: In function ‘canRead’:
mw_wrapperCANChannel.c:65:22: warning: too many arguments for format [-Wformat-extra-args]
65 | LOG_PRINT(stdout,"REQUEST_CAN_Read: n",0);
| ^~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:98:26: warning: too many arguments for format [-Wformat-extra-args]
98 | LOG_PRINT(stdout,"CANChannel: Read successful n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
mw_wrapperCANChannel.c:100:26: warning: too many arguments for format [-Wformat-extra-args]
100 | LOG_PRINT(stdout,"CANChannel: Read failed n",0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
common.h:12:51: note: in definition of macro ‘LOG_PRINT’
12 | #define LOG_PRINT(fd, format, …) fprintf(fd, format, __VA_ARGS__); fflush(fd)
| ^~~~~~
picam.c:19:10: fatal error: RaspiCamControl.h: No such file or directory
19 | #include "RaspiCamControl.h"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:81: obj/picam.o] Error 1
STDOUT: make: Entering directory ‘/opt/MATLAB/mw_server_v22.1.0’
[Compiling] IO_wrapperv4l2.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ IO_wrapperv4l2.c
-o obj/IO_wrapperv4l2.o
[Compiling] MW_PWM.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ MW_PWM.c -o
obj/MW_PWM.o
[Compiling] MW_pigs.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ MW_pigs.c -o
obj/MW_pigs.o
[Compiling] sharedServer.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ sharedServer.c
-o obj/sharedServer.o
[Compiling] IO_wrapperCameraboard.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_
IO_wrapperCameraboard.c -o obj/IO_wrapperCameraboard.o
[Compiling] mw_wrapperCANChannel.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_
mw_wrapperCANChannel.c -o obj/mw_wrapperCANChannel.o
[Compiling] LED.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ LED.c -o
obj/LED.o
[Compiling] picam.c
gcc -c -g -O0 -D_DEBUG -Wall -I/opt/userland -I/opt/userland/host_applications/linux/libs/bcm_host/include
-I/opt/userland/interface/vcos -I/opt/userland/interface/vcos/pthreads -I/opt/userland/interface/vmcs_host/linux
-I/opt/userland/host_applications/linux/apps/raspicam -I/opt/nanomsg/include -Winline -pipe -D_DEBUG -D_MATLABIO_ picam.c -o
obj/picam.o
make: Leaving directory ‘/opt/MATLAB/mw_server_v22.1.0’ raspberry pi, raspi(), matlab MATLAB Answers — New Questions
trying to find the polynomial equation representing the given four second-order differential equations
For the following problem in the first image i get the error pictured in the third image when trying to solve the 4 second-order differential equations using numerical methods. I am trying to use Heun’s method for solving second-order differential equations and from here getting the x and y values corresponding to the function. Then taking these values and putting them into the least-square method to find the polynomial equation that best represents the system of equations. The third image is of the free-body diagram representing this system, then follows the code, if anyone can see where I need to adjust the code to run correctly this would be much appreciated.
MATLAB CODE:
% 4 Equations representing the system working with
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
clc
clear
%————————————————-SYSTEM_PARAMETERS———————————————————————————————————————————————————-
Ic=1356; %kg-m^2
Mb=730; %kg
Mf=59; %kg
Mr=45; %kg
Kf=23000; %N/m
Ksf=18750; %N/m
Kr=16182; %N/m
Ksr=12574; %N/m
Bsf=100; %N*s/m
Bsr=100; %N*s/m
L1=1.45; %m
L2=1.39; %m
L3=0.67; %m
t=[0:20]; % time from 0 to 20 seconds
%Initial Conditions x=(0)=0 dXf/dt(0)=y(0)=0 ;
%t from 0 to 1 h=dx=0.5;
x0=0; %x at initial condition
y0=0; %y at initial condition
t0=0; %t at the start
dx=5; %delta(x) or h
h=dx;
tm=20; %what value of (x) you are ending at
syms Xf(t) Xr(t) Xb(t) theta(t) fa(t) Y
Xf_1=diff(Xf,t);
Xf_2=diff(Xf,t,2);
Xr_1=diff(Xr,t);
Xr_2=diff(Xr,t,2);
Xb_1=diff(Xb,t);
Xb_2=diff(Xb,t,2);
theta_1=diff(theta,t);
theta_2=diff(theta,t,2);
%%%% MfXf"=Ksf((Xb-(L1*theta))-Xf)+Bsf((Xb’-(L1*theta’))-Xf’)-(Kf*Xf);
%anything in [] below indicates a deritive
% Mf*[(d^2Xf)/(dt^2)] = Ksf*((Xb-(L1*theta))-Xf)+Bsf*(([(dXb)/(dt)]-(L1*[(dtheta)/(dt)])-[(dXf)/(dt)])-(Kf*Xf);
Mf*Xf_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1)-Xf_1)-(Kf*Xf))))==0;
f2_YF=isolate(Mf*Xf_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1)-Xf_1)-(Kf*Xf))))==0,Xf_2);
f2_Yf=subs(f2_YF,[Xf_2 Xf_1],[Xf_1 Y])
f2_Yf=rhs(f2_Yf)
%dXf/dt=y_f–>ASSUMED
%dXf/dt=f1_f(x,y,t)=y_f
%dYf/dt=f2_f(x,y,t)=f2_Yf
%%%% MrXr"=Ksr((Xb+(L2*theta))-Xr)+Bsr((Xb’+(L2*theta’))-Xr’)-(Kr*Xr);
%anything in [] below indicates a deritive
% Mf*[(d^2Xr)/(dt^2)] = Ksf*((Xb-(L1*theta))-Xf)+Bsr*(([(dXb)/(dt)]-(L2*[(dtheta)/(dt)])-[(dXr)/(dt)])-(Kf*Xf);
Mr*Xr_2-((Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1)-(Kr*Xr)))==0;
f2_YR=isolate(Mr*Xr_2-((Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1)-(Kr*Xr)))==0,Xr_2);
f2_Yr=subs(f2_YR,[Xr_2 Xr_1],[Xr_1 Y])
f2_Yr=rhs(f2_Yr)
%dXr/dt=y_r–>ASSUMED
%dXr/dt=f1_r(x,y,t)=y_r
%dYr/dt=f2_r(x,y,t)=f2_Yr
%%%% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
%anything in [] below indicates a deritive fa(t) given as 10e^(-(5t))
% Mb*[(d^2Xb)/(dt^2)]=Ksf*((Xb-(L1*theta))-Xf)+Bsf*(([(dXb)/(dt)]-(L1*[(dtheta)/(dt)]))-[(dXf)/(dt)])+Ksr*([Xb+(L2*theta)]-Xr)+Bsr( (([(dXb)/(dt)]+(L2*[(dtheta)/(dt)]))-[(dXr)/(dt)]))+fa(t);
Mb*Xb_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1))-Xf_1)+Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1))==(10*exp(-(5*t))));
f2_YB=Xb_2==(-Ksf*((Xb-(L1*theta))-Xf)-Bsf*((Xb_1-(L1*theta_1))-Xf_1)-Ksr*((Xb+(L2*theta))-Xr)-Bsr*((Xb_1+(L2*theta_1))-Xr_1)+(10*exp(-(5*t))))/Mb;
f2_Yb=subs(f2_YB,[Xb_2 Xb_1],[Xb_1 Y])
f2_Yb=rhs(f2_Yb)
%dXb/dt=y–>ASSUMED
%dXb/dt=f1_b(x,y,t)=y_b
%dYb/dt=f2_b(x,y,t)=f2_Yb
%%%% Ic*theta"={-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf’-(L1*theta’))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr’+(L2*theta’))*L2)+(fa(t)*L3)};
%anything in [] below indicates a deritive fa(t) given as 10e^(-(5t))
%Ic*[(d^2theta)/(dt^2)]=(-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*([dXf/dt]-(L1*[(dtheta)/(dt)]))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*([(dXr)/(dt)]+(L2*[(dtheta)/(dt)]))*L2)+(fa(t)*L3));
theta_2==((-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf_1-(L1*theta_1))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr_1+(L2*theta_1))*L2)+((10*exp(-(5*t)))*L3)))/Ic;
Ic*theta_2-(-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf_1-(L1*theta_1))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr_1+(L2*theta_1))*L2))==(10*exp(-(5*t)))*L3;
f2_YTheta=theta_2==((-Ksf*(Xf-(Xb-(L1*theta)))*L1) – (Bsf*(Xf_1-(Xb_1-(L1*theta_1)))*L1) + (Ksr*(Xr-(Xb+(L2*theta)))*L2) + (Bsr*(Xr_1-(Xb_1+(L2*theta_1)))*L2) + ((10*exp(-(5*t)))*L3))/Ic;
f2_Ytheta=subs(f2_YTheta,[theta_2 theta_1],[theta_1 Y])
f2_Ytheta=rhs(f2_Ytheta)
%dXb/dt=y–>ASSUMED
%dXb/dt=f1_theta(x,y,t)=y_theta
%dYb/dt=f2_theta(x,y,t)=f2_Ytheta
syms x y t
%==INPUT SECTION==%
fx_f=@(x,y,t)y_f;
fy_f=@(x,y,t)f2_Yf;
fx_r=@(x,y,t)y_r;
fy_r=@(x,y,t)f2_Yr;
fx_b=@(x,y,t)y_b;
fy_b=@(x,y,t)f2_Yb;
fx_theta=@(x,y,t)y_theta;
fy_theta=@(x,y,t)f2_Ytheta;
%==CALCULATIONS SECTION==%
tn=t0:h:tm;
xn_f(1)=x0;
yn_f=y0;
xn_r(1)=x0;
yn_r=y0;
xn_b(1)=x0;
yn_b=y0;
xn_theta(1)=x0;
yn_theta=y0;
for i=1:length(tn)
%==EULER’S METHOD
xn_f(i+1)=xn_f(i)+fx_f(xn_f(i),yn_f(i),tn(i))*h;
yn_f(i+1)=yn_f(i)+fy_f(xn_f(i),yn_f(i),tn(i))*h;
xn_r(i+1)=xn_r(i)+fx_r(xn_r(i),yn_r(i),tn(i))*h;
yn_r(i+1)=yn_r(i)+fy_r(xn_r(i),yn_r(i),tn(i))*h;
xn_b(i+1)=xn_b(i)+fx_b(xn_b(i),yn_b(i),tn(i))*h;
yn_b(i+1)=yn_b(i)+fy_b(xn_b(i),yn_b(i),tn(i))*h;
xn_theta(i+1)=xn_theta(i)+fx_theta(xn_theta(i),yn_theta(i),tn(i))*h;
yn_theta(i+1)=yn_theta(i)+fy_theta(xn_theta(i),yn_theta(i),tn(i))*h;
%==NEXT 3 LINES ARE FOR HEUN’S METHOD
tn(i+1)=tn(i)+h;
xn_f(i+1)=xn_f(i)+0.5*(fx_f(xn_f(i),yn_f(i),tn(i))+fx_f(xn_f(i+1),yn_f(i+1),tn(i+1)))*h;
yn_f(i+1)=yn_f(i)+0.5*(fy_f(xn_f(i),yn_f(i),tn(i))+fy_f(xn_f(i+1),yn_f(i+1),tn(i+1)))*h;
xn_r(i+1)=xn_r(i)+0.5*(fx_r(xn_r(i),yn_r(i),tn(i))+fx_r(xn_r(i+1),yn_r(i+1),tn(i+1)))*h;
yn_r(i+1)=yn_r(i)+0.5*(fy_r(xn_r(i),yn_r(i),tn(i))+fy_r(xn_r(i+1),yn_r(i+1),tn(i+1)))*h;
xn_b(i+1)=xn_b(i)+0.5*(fx_b(xn_b(i),yn_b(i),tn(i))+fx_b(xn_b(i+1),yn_b(i+1),tn(i+1)))*h;
yn_b(i+1)=yn_b(i)+0.5*(fy_b(xn_b(i),yn_b(i),tn(i))+fy_b(xn_b(i+1),yn_b(i+1),tn(i+1)))*h;
xn_theta(i+1)=xn_theta(i)+0.5*(fx_theta(xn_theta(i),yn_theta(i),tn(i))+fx_theta(xn-theta(i+1),yn_theta(i+1),tn(i+1)))*h;
yn_theta(i+1)=yn_theta(i)+0.5*(fy_theta(xn_theta(i),yn_theta(i),tn(i))+fy_theta(xn-theta(i+1),yn_theta(i+1),tn(i+1)))*h;
fprintf(‘t=%0.2ft x_f=%0.3ft y_f=%0.3ft x_r=%0.3ft y_r=%0.3ft x_b=%0.3ft y_b=%0.3ft x_theta=%0.3ft y_theta=%0.3fn’,tn(i),xn_f(i),yn_f(i),xn_r(i),yn_r(i),xn_b(i),yn_b(i),xn_theta(i),yn_theta(i))
end
%input
x=[‘x values from Heuns method’];
y=[‘y values from Heuns method’];
n=4; %order of the polynomial you want to find
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION
x=x; %x-cordinates from data-input; independent vairiables
y=y; %y-cordinates from data-output; dependent vairiables
%CALCULATIONS SECTION
k=length(x); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(x.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(y.*x.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%
%STANDARD DEVIATION
Y_bar=mean(y); %ADVERAGE OF y
St=sum((y-Y_bar).^2);
SD=sqrt(St/(k-1)); %STANDARD DEVIATION
%STANDARD ERROR
for i=1:m;
T(:,i)=a(i)*x.^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
end
for i=1:k
y_hat(i)=sum(T(i,:));
end
Sr=sum((y-y_hat).^2);
Se=sqrt(Sr/(k-(n+1))); %STANDARD ERROR-Se
%COEFFICIENT OF DETERMINATION
Cd=(St-Sr)/St %COEFFICIENT OF DETERMINATION (r^2)
fprintf(‘For n=%d. Coefficient of Determination=%0.5fn’,n,Cd)
%EQUATION FOR THE POLYNOMIAL
syms x y
%for n=2 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2
%for n=3 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3
%for n=4 activate lines below
a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4
%for n=5 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5
%for n=6 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7)
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6
%for n=7 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7
%for n=8 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8
%for n=9 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9For the following problem in the first image i get the error pictured in the third image when trying to solve the 4 second-order differential equations using numerical methods. I am trying to use Heun’s method for solving second-order differential equations and from here getting the x and y values corresponding to the function. Then taking these values and putting them into the least-square method to find the polynomial equation that best represents the system of equations. The third image is of the free-body diagram representing this system, then follows the code, if anyone can see where I need to adjust the code to run correctly this would be much appreciated.
MATLAB CODE:
% 4 Equations representing the system working with
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
clc
clear
%————————————————-SYSTEM_PARAMETERS———————————————————————————————————————————————————-
Ic=1356; %kg-m^2
Mb=730; %kg
Mf=59; %kg
Mr=45; %kg
Kf=23000; %N/m
Ksf=18750; %N/m
Kr=16182; %N/m
Ksr=12574; %N/m
Bsf=100; %N*s/m
Bsr=100; %N*s/m
L1=1.45; %m
L2=1.39; %m
L3=0.67; %m
t=[0:20]; % time from 0 to 20 seconds
%Initial Conditions x=(0)=0 dXf/dt(0)=y(0)=0 ;
%t from 0 to 1 h=dx=0.5;
x0=0; %x at initial condition
y0=0; %y at initial condition
t0=0; %t at the start
dx=5; %delta(x) or h
h=dx;
tm=20; %what value of (x) you are ending at
syms Xf(t) Xr(t) Xb(t) theta(t) fa(t) Y
Xf_1=diff(Xf,t);
Xf_2=diff(Xf,t,2);
Xr_1=diff(Xr,t);
Xr_2=diff(Xr,t,2);
Xb_1=diff(Xb,t);
Xb_2=diff(Xb,t,2);
theta_1=diff(theta,t);
theta_2=diff(theta,t,2);
%%%% MfXf"=Ksf((Xb-(L1*theta))-Xf)+Bsf((Xb’-(L1*theta’))-Xf’)-(Kf*Xf);
%anything in [] below indicates a deritive
% Mf*[(d^2Xf)/(dt^2)] = Ksf*((Xb-(L1*theta))-Xf)+Bsf*(([(dXb)/(dt)]-(L1*[(dtheta)/(dt)])-[(dXf)/(dt)])-(Kf*Xf);
Mf*Xf_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1)-Xf_1)-(Kf*Xf))))==0;
f2_YF=isolate(Mf*Xf_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1)-Xf_1)-(Kf*Xf))))==0,Xf_2);
f2_Yf=subs(f2_YF,[Xf_2 Xf_1],[Xf_1 Y])
f2_Yf=rhs(f2_Yf)
%dXf/dt=y_f–>ASSUMED
%dXf/dt=f1_f(x,y,t)=y_f
%dYf/dt=f2_f(x,y,t)=f2_Yf
%%%% MrXr"=Ksr((Xb+(L2*theta))-Xr)+Bsr((Xb’+(L2*theta’))-Xr’)-(Kr*Xr);
%anything in [] below indicates a deritive
% Mf*[(d^2Xr)/(dt^2)] = Ksf*((Xb-(L1*theta))-Xf)+Bsr*(([(dXb)/(dt)]-(L2*[(dtheta)/(dt)])-[(dXr)/(dt)])-(Kf*Xf);
Mr*Xr_2-((Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1)-(Kr*Xr)))==0;
f2_YR=isolate(Mr*Xr_2-((Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1)-(Kr*Xr)))==0,Xr_2);
f2_Yr=subs(f2_YR,[Xr_2 Xr_1],[Xr_1 Y])
f2_Yr=rhs(f2_Yr)
%dXr/dt=y_r–>ASSUMED
%dXr/dt=f1_r(x,y,t)=y_r
%dYr/dt=f2_r(x,y,t)=f2_Yr
%%%% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
%anything in [] below indicates a deritive fa(t) given as 10e^(-(5t))
% Mb*[(d^2Xb)/(dt^2)]=Ksf*((Xb-(L1*theta))-Xf)+Bsf*(([(dXb)/(dt)]-(L1*[(dtheta)/(dt)]))-[(dXf)/(dt)])+Ksr*([Xb+(L2*theta)]-Xr)+Bsr( (([(dXb)/(dt)]+(L2*[(dtheta)/(dt)]))-[(dXr)/(dt)]))+fa(t);
Mb*Xb_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1))-Xf_1)+Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1))==(10*exp(-(5*t))));
f2_YB=Xb_2==(-Ksf*((Xb-(L1*theta))-Xf)-Bsf*((Xb_1-(L1*theta_1))-Xf_1)-Ksr*((Xb+(L2*theta))-Xr)-Bsr*((Xb_1+(L2*theta_1))-Xr_1)+(10*exp(-(5*t))))/Mb;
f2_Yb=subs(f2_YB,[Xb_2 Xb_1],[Xb_1 Y])
f2_Yb=rhs(f2_Yb)
%dXb/dt=y–>ASSUMED
%dXb/dt=f1_b(x,y,t)=y_b
%dYb/dt=f2_b(x,y,t)=f2_Yb
%%%% Ic*theta"={-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf’-(L1*theta’))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr’+(L2*theta’))*L2)+(fa(t)*L3)};
%anything in [] below indicates a deritive fa(t) given as 10e^(-(5t))
%Ic*[(d^2theta)/(dt^2)]=(-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*([dXf/dt]-(L1*[(dtheta)/(dt)]))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*([(dXr)/(dt)]+(L2*[(dtheta)/(dt)]))*L2)+(fa(t)*L3));
theta_2==((-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf_1-(L1*theta_1))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr_1+(L2*theta_1))*L2)+((10*exp(-(5*t)))*L3)))/Ic;
Ic*theta_2-(-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf_1-(L1*theta_1))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr_1+(L2*theta_1))*L2))==(10*exp(-(5*t)))*L3;
f2_YTheta=theta_2==((-Ksf*(Xf-(Xb-(L1*theta)))*L1) – (Bsf*(Xf_1-(Xb_1-(L1*theta_1)))*L1) + (Ksr*(Xr-(Xb+(L2*theta)))*L2) + (Bsr*(Xr_1-(Xb_1+(L2*theta_1)))*L2) + ((10*exp(-(5*t)))*L3))/Ic;
f2_Ytheta=subs(f2_YTheta,[theta_2 theta_1],[theta_1 Y])
f2_Ytheta=rhs(f2_Ytheta)
%dXb/dt=y–>ASSUMED
%dXb/dt=f1_theta(x,y,t)=y_theta
%dYb/dt=f2_theta(x,y,t)=f2_Ytheta
syms x y t
%==INPUT SECTION==%
fx_f=@(x,y,t)y_f;
fy_f=@(x,y,t)f2_Yf;
fx_r=@(x,y,t)y_r;
fy_r=@(x,y,t)f2_Yr;
fx_b=@(x,y,t)y_b;
fy_b=@(x,y,t)f2_Yb;
fx_theta=@(x,y,t)y_theta;
fy_theta=@(x,y,t)f2_Ytheta;
%==CALCULATIONS SECTION==%
tn=t0:h:tm;
xn_f(1)=x0;
yn_f=y0;
xn_r(1)=x0;
yn_r=y0;
xn_b(1)=x0;
yn_b=y0;
xn_theta(1)=x0;
yn_theta=y0;
for i=1:length(tn)
%==EULER’S METHOD
xn_f(i+1)=xn_f(i)+fx_f(xn_f(i),yn_f(i),tn(i))*h;
yn_f(i+1)=yn_f(i)+fy_f(xn_f(i),yn_f(i),tn(i))*h;
xn_r(i+1)=xn_r(i)+fx_r(xn_r(i),yn_r(i),tn(i))*h;
yn_r(i+1)=yn_r(i)+fy_r(xn_r(i),yn_r(i),tn(i))*h;
xn_b(i+1)=xn_b(i)+fx_b(xn_b(i),yn_b(i),tn(i))*h;
yn_b(i+1)=yn_b(i)+fy_b(xn_b(i),yn_b(i),tn(i))*h;
xn_theta(i+1)=xn_theta(i)+fx_theta(xn_theta(i),yn_theta(i),tn(i))*h;
yn_theta(i+1)=yn_theta(i)+fy_theta(xn_theta(i),yn_theta(i),tn(i))*h;
%==NEXT 3 LINES ARE FOR HEUN’S METHOD
tn(i+1)=tn(i)+h;
xn_f(i+1)=xn_f(i)+0.5*(fx_f(xn_f(i),yn_f(i),tn(i))+fx_f(xn_f(i+1),yn_f(i+1),tn(i+1)))*h;
yn_f(i+1)=yn_f(i)+0.5*(fy_f(xn_f(i),yn_f(i),tn(i))+fy_f(xn_f(i+1),yn_f(i+1),tn(i+1)))*h;
xn_r(i+1)=xn_r(i)+0.5*(fx_r(xn_r(i),yn_r(i),tn(i))+fx_r(xn_r(i+1),yn_r(i+1),tn(i+1)))*h;
yn_r(i+1)=yn_r(i)+0.5*(fy_r(xn_r(i),yn_r(i),tn(i))+fy_r(xn_r(i+1),yn_r(i+1),tn(i+1)))*h;
xn_b(i+1)=xn_b(i)+0.5*(fx_b(xn_b(i),yn_b(i),tn(i))+fx_b(xn_b(i+1),yn_b(i+1),tn(i+1)))*h;
yn_b(i+1)=yn_b(i)+0.5*(fy_b(xn_b(i),yn_b(i),tn(i))+fy_b(xn_b(i+1),yn_b(i+1),tn(i+1)))*h;
xn_theta(i+1)=xn_theta(i)+0.5*(fx_theta(xn_theta(i),yn_theta(i),tn(i))+fx_theta(xn-theta(i+1),yn_theta(i+1),tn(i+1)))*h;
yn_theta(i+1)=yn_theta(i)+0.5*(fy_theta(xn_theta(i),yn_theta(i),tn(i))+fy_theta(xn-theta(i+1),yn_theta(i+1),tn(i+1)))*h;
fprintf(‘t=%0.2ft x_f=%0.3ft y_f=%0.3ft x_r=%0.3ft y_r=%0.3ft x_b=%0.3ft y_b=%0.3ft x_theta=%0.3ft y_theta=%0.3fn’,tn(i),xn_f(i),yn_f(i),xn_r(i),yn_r(i),xn_b(i),yn_b(i),xn_theta(i),yn_theta(i))
end
%input
x=[‘x values from Heuns method’];
y=[‘y values from Heuns method’];
n=4; %order of the polynomial you want to find
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION
x=x; %x-cordinates from data-input; independent vairiables
y=y; %y-cordinates from data-output; dependent vairiables
%CALCULATIONS SECTION
k=length(x); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(x.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(y.*x.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%
%STANDARD DEVIATION
Y_bar=mean(y); %ADVERAGE OF y
St=sum((y-Y_bar).^2);
SD=sqrt(St/(k-1)); %STANDARD DEVIATION
%STANDARD ERROR
for i=1:m;
T(:,i)=a(i)*x.^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
end
for i=1:k
y_hat(i)=sum(T(i,:));
end
Sr=sum((y-y_hat).^2);
Se=sqrt(Sr/(k-(n+1))); %STANDARD ERROR-Se
%COEFFICIENT OF DETERMINATION
Cd=(St-Sr)/St %COEFFICIENT OF DETERMINATION (r^2)
fprintf(‘For n=%d. Coefficient of Determination=%0.5fn’,n,Cd)
%EQUATION FOR THE POLYNOMIAL
syms x y
%for n=2 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2
%for n=3 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3
%for n=4 activate lines below
a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4
%for n=5 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5
%for n=6 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7)
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6
%for n=7 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7
%for n=8 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8
%for n=9 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9 For the following problem in the first image i get the error pictured in the third image when trying to solve the 4 second-order differential equations using numerical methods. I am trying to use Heun’s method for solving second-order differential equations and from here getting the x and y values corresponding to the function. Then taking these values and putting them into the least-square method to find the polynomial equation that best represents the system of equations. The third image is of the free-body diagram representing this system, then follows the code, if anyone can see where I need to adjust the code to run correctly this would be much appreciated.
MATLAB CODE:
% 4 Equations representing the system working with
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
clc
clear
%————————————————-SYSTEM_PARAMETERS———————————————————————————————————————————————————-
Ic=1356; %kg-m^2
Mb=730; %kg
Mf=59; %kg
Mr=45; %kg
Kf=23000; %N/m
Ksf=18750; %N/m
Kr=16182; %N/m
Ksr=12574; %N/m
Bsf=100; %N*s/m
Bsr=100; %N*s/m
L1=1.45; %m
L2=1.39; %m
L3=0.67; %m
t=[0:20]; % time from 0 to 20 seconds
%Initial Conditions x=(0)=0 dXf/dt(0)=y(0)=0 ;
%t from 0 to 1 h=dx=0.5;
x0=0; %x at initial condition
y0=0; %y at initial condition
t0=0; %t at the start
dx=5; %delta(x) or h
h=dx;
tm=20; %what value of (x) you are ending at
syms Xf(t) Xr(t) Xb(t) theta(t) fa(t) Y
Xf_1=diff(Xf,t);
Xf_2=diff(Xf,t,2);
Xr_1=diff(Xr,t);
Xr_2=diff(Xr,t,2);
Xb_1=diff(Xb,t);
Xb_2=diff(Xb,t,2);
theta_1=diff(theta,t);
theta_2=diff(theta,t,2);
%%%% MfXf"=Ksf((Xb-(L1*theta))-Xf)+Bsf((Xb’-(L1*theta’))-Xf’)-(Kf*Xf);
%anything in [] below indicates a deritive
% Mf*[(d^2Xf)/(dt^2)] = Ksf*((Xb-(L1*theta))-Xf)+Bsf*(([(dXb)/(dt)]-(L1*[(dtheta)/(dt)])-[(dXf)/(dt)])-(Kf*Xf);
Mf*Xf_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1)-Xf_1)-(Kf*Xf))))==0;
f2_YF=isolate(Mf*Xf_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1)-Xf_1)-(Kf*Xf))))==0,Xf_2);
f2_Yf=subs(f2_YF,[Xf_2 Xf_1],[Xf_1 Y])
f2_Yf=rhs(f2_Yf)
%dXf/dt=y_f–>ASSUMED
%dXf/dt=f1_f(x,y,t)=y_f
%dYf/dt=f2_f(x,y,t)=f2_Yf
%%%% MrXr"=Ksr((Xb+(L2*theta))-Xr)+Bsr((Xb’+(L2*theta’))-Xr’)-(Kr*Xr);
%anything in [] below indicates a deritive
% Mf*[(d^2Xr)/(dt^2)] = Ksf*((Xb-(L1*theta))-Xf)+Bsr*(([(dXb)/(dt)]-(L2*[(dtheta)/(dt)])-[(dXr)/(dt)])-(Kf*Xf);
Mr*Xr_2-((Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1)-(Kr*Xr)))==0;
f2_YR=isolate(Mr*Xr_2-((Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1)-(Kr*Xr)))==0,Xr_2);
f2_Yr=subs(f2_YR,[Xr_2 Xr_1],[Xr_1 Y])
f2_Yr=rhs(f2_Yr)
%dXr/dt=y_r–>ASSUMED
%dXr/dt=f1_r(x,y,t)=y_r
%dYr/dt=f2_r(x,y,t)=f2_Yr
%%%% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
%anything in [] below indicates a deritive fa(t) given as 10e^(-(5t))
% Mb*[(d^2Xb)/(dt^2)]=Ksf*((Xb-(L1*theta))-Xf)+Bsf*(([(dXb)/(dt)]-(L1*[(dtheta)/(dt)]))-[(dXf)/(dt)])+Ksr*([Xb+(L2*theta)]-Xr)+Bsr( (([(dXb)/(dt)]+(L2*[(dtheta)/(dt)]))-[(dXr)/(dt)]))+fa(t);
Mb*Xb_2-((Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Xb_1-(L1*theta_1))-Xf_1)+Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Xb_1+(L2*theta_1))-Xr_1))==(10*exp(-(5*t))));
f2_YB=Xb_2==(-Ksf*((Xb-(L1*theta))-Xf)-Bsf*((Xb_1-(L1*theta_1))-Xf_1)-Ksr*((Xb+(L2*theta))-Xr)-Bsr*((Xb_1+(L2*theta_1))-Xr_1)+(10*exp(-(5*t))))/Mb;
f2_Yb=subs(f2_YB,[Xb_2 Xb_1],[Xb_1 Y])
f2_Yb=rhs(f2_Yb)
%dXb/dt=y–>ASSUMED
%dXb/dt=f1_b(x,y,t)=y_b
%dYb/dt=f2_b(x,y,t)=f2_Yb
%%%% Ic*theta"={-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf’-(L1*theta’))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr’+(L2*theta’))*L2)+(fa(t)*L3)};
%anything in [] below indicates a deritive fa(t) given as 10e^(-(5t))
%Ic*[(d^2theta)/(dt^2)]=(-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*([dXf/dt]-(L1*[(dtheta)/(dt)]))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*([(dXr)/(dt)]+(L2*[(dtheta)/(dt)]))*L2)+(fa(t)*L3));
theta_2==((-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf_1-(L1*theta_1))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr_1+(L2*theta_1))*L2)+((10*exp(-(5*t)))*L3)))/Ic;
Ic*theta_2-(-(Ksf*(Xf-(L1*theta))*L1)-(Bsf*(Xf_1-(L1*theta_1))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Xr_1+(L2*theta_1))*L2))==(10*exp(-(5*t)))*L3;
f2_YTheta=theta_2==((-Ksf*(Xf-(Xb-(L1*theta)))*L1) – (Bsf*(Xf_1-(Xb_1-(L1*theta_1)))*L1) + (Ksr*(Xr-(Xb+(L2*theta)))*L2) + (Bsr*(Xr_1-(Xb_1+(L2*theta_1)))*L2) + ((10*exp(-(5*t)))*L3))/Ic;
f2_Ytheta=subs(f2_YTheta,[theta_2 theta_1],[theta_1 Y])
f2_Ytheta=rhs(f2_Ytheta)
%dXb/dt=y–>ASSUMED
%dXb/dt=f1_theta(x,y,t)=y_theta
%dYb/dt=f2_theta(x,y,t)=f2_Ytheta
syms x y t
%==INPUT SECTION==%
fx_f=@(x,y,t)y_f;
fy_f=@(x,y,t)f2_Yf;
fx_r=@(x,y,t)y_r;
fy_r=@(x,y,t)f2_Yr;
fx_b=@(x,y,t)y_b;
fy_b=@(x,y,t)f2_Yb;
fx_theta=@(x,y,t)y_theta;
fy_theta=@(x,y,t)f2_Ytheta;
%==CALCULATIONS SECTION==%
tn=t0:h:tm;
xn_f(1)=x0;
yn_f=y0;
xn_r(1)=x0;
yn_r=y0;
xn_b(1)=x0;
yn_b=y0;
xn_theta(1)=x0;
yn_theta=y0;
for i=1:length(tn)
%==EULER’S METHOD
xn_f(i+1)=xn_f(i)+fx_f(xn_f(i),yn_f(i),tn(i))*h;
yn_f(i+1)=yn_f(i)+fy_f(xn_f(i),yn_f(i),tn(i))*h;
xn_r(i+1)=xn_r(i)+fx_r(xn_r(i),yn_r(i),tn(i))*h;
yn_r(i+1)=yn_r(i)+fy_r(xn_r(i),yn_r(i),tn(i))*h;
xn_b(i+1)=xn_b(i)+fx_b(xn_b(i),yn_b(i),tn(i))*h;
yn_b(i+1)=yn_b(i)+fy_b(xn_b(i),yn_b(i),tn(i))*h;
xn_theta(i+1)=xn_theta(i)+fx_theta(xn_theta(i),yn_theta(i),tn(i))*h;
yn_theta(i+1)=yn_theta(i)+fy_theta(xn_theta(i),yn_theta(i),tn(i))*h;
%==NEXT 3 LINES ARE FOR HEUN’S METHOD
tn(i+1)=tn(i)+h;
xn_f(i+1)=xn_f(i)+0.5*(fx_f(xn_f(i),yn_f(i),tn(i))+fx_f(xn_f(i+1),yn_f(i+1),tn(i+1)))*h;
yn_f(i+1)=yn_f(i)+0.5*(fy_f(xn_f(i),yn_f(i),tn(i))+fy_f(xn_f(i+1),yn_f(i+1),tn(i+1)))*h;
xn_r(i+1)=xn_r(i)+0.5*(fx_r(xn_r(i),yn_r(i),tn(i))+fx_r(xn_r(i+1),yn_r(i+1),tn(i+1)))*h;
yn_r(i+1)=yn_r(i)+0.5*(fy_r(xn_r(i),yn_r(i),tn(i))+fy_r(xn_r(i+1),yn_r(i+1),tn(i+1)))*h;
xn_b(i+1)=xn_b(i)+0.5*(fx_b(xn_b(i),yn_b(i),tn(i))+fx_b(xn_b(i+1),yn_b(i+1),tn(i+1)))*h;
yn_b(i+1)=yn_b(i)+0.5*(fy_b(xn_b(i),yn_b(i),tn(i))+fy_b(xn_b(i+1),yn_b(i+1),tn(i+1)))*h;
xn_theta(i+1)=xn_theta(i)+0.5*(fx_theta(xn_theta(i),yn_theta(i),tn(i))+fx_theta(xn-theta(i+1),yn_theta(i+1),tn(i+1)))*h;
yn_theta(i+1)=yn_theta(i)+0.5*(fy_theta(xn_theta(i),yn_theta(i),tn(i))+fy_theta(xn-theta(i+1),yn_theta(i+1),tn(i+1)))*h;
fprintf(‘t=%0.2ft x_f=%0.3ft y_f=%0.3ft x_r=%0.3ft y_r=%0.3ft x_b=%0.3ft y_b=%0.3ft x_theta=%0.3ft y_theta=%0.3fn’,tn(i),xn_f(i),yn_f(i),xn_r(i),yn_r(i),xn_b(i),yn_b(i),xn_theta(i),yn_theta(i))
end
%input
x=[‘x values from Heuns method’];
y=[‘y values from Heuns method’];
n=4; %order of the polynomial you want to find
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION
x=x; %x-cordinates from data-input; independent vairiables
y=y; %y-cordinates from data-output; dependent vairiables
%CALCULATIONS SECTION
k=length(x); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(x.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(y.*x.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%
%STANDARD DEVIATION
Y_bar=mean(y); %ADVERAGE OF y
St=sum((y-Y_bar).^2);
SD=sqrt(St/(k-1)); %STANDARD DEVIATION
%STANDARD ERROR
for i=1:m;
T(:,i)=a(i)*x.^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
end
for i=1:k
y_hat(i)=sum(T(i,:));
end
Sr=sum((y-y_hat).^2);
Se=sqrt(Sr/(k-(n+1))); %STANDARD ERROR-Se
%COEFFICIENT OF DETERMINATION
Cd=(St-Sr)/St %COEFFICIENT OF DETERMINATION (r^2)
fprintf(‘For n=%d. Coefficient of Determination=%0.5fn’,n,Cd)
%EQUATION FOR THE POLYNOMIAL
syms x y
%for n=2 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2
%for n=3 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3
%for n=4 activate lines below
a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);
sympref("FloatingPointOutput",true);
y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4
%for n=5 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5
%for n=6 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7)
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6
%for n=7 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7
%for n=8 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8
%for n=9 activate lines below
%a0=a(:,1);a1=a(:,1);a2=a(:,3);a3=a(:,4);a4=a(:,5);a5=a(:,6);a6=a(:,7);a7=a(:,8);a8=a(:,9);a9=a(:,10);
%sympref("FloatingPointOutput",true);
%y=a0+a1*x+a2*x.^2+a3*x.^3+a4*x.^4+a5*x.^5+a6*x.^6+a7*x.^7+a8*x.^8+a9*x.^9 solving multiple dependent second ord, numerical methods, polynomial equation representing ord MATLAB Answers — New Questions
How to compile a Standalone App which requires Python?
I am trying to compile a Standalone App with App designer.
The goal should be that other user can open the App without having Matlab installed.
The App workes on App Designer perfectly. Even if I compile the App and open it on my computer everything runs.
However, if I open the App on an other computer (without MATLAB, Python and CoolProp) the App opens but the calculation can’t be done.
I guess the problem is the missing Python and/or CoolProp on the second Computer.
My code uses this function:
rho=py.CoolProp.CoolProp.PropsSI(‘D’,’T’,273.15+ T_gc_out ,’P’,p_h,KM)
Is there a way to compile the App including the required Python and CoolProp software to run my programm? I want to include these files, or codes in the app such that the other users don’t have to download Python and CoolProp separately.I am trying to compile a Standalone App with App designer.
The goal should be that other user can open the App without having Matlab installed.
The App workes on App Designer perfectly. Even if I compile the App and open it on my computer everything runs.
However, if I open the App on an other computer (without MATLAB, Python and CoolProp) the App opens but the calculation can’t be done.
I guess the problem is the missing Python and/or CoolProp on the second Computer.
My code uses this function:
rho=py.CoolProp.CoolProp.PropsSI(‘D’,’T’,273.15+ T_gc_out ,’P’,p_h,KM)
Is there a way to compile the App including the required Python and CoolProp software to run my programm? I want to include these files, or codes in the app such that the other users don’t have to download Python and CoolProp separately. I am trying to compile a Standalone App with App designer.
The goal should be that other user can open the App without having Matlab installed.
The App workes on App Designer perfectly. Even if I compile the App and open it on my computer everything runs.
However, if I open the App on an other computer (without MATLAB, Python and CoolProp) the App opens but the calculation can’t be done.
I guess the problem is the missing Python and/or CoolProp on the second Computer.
My code uses this function:
rho=py.CoolProp.CoolProp.PropsSI(‘D’,’T’,273.15+ T_gc_out ,’P’,p_h,KM)
Is there a way to compile the App including the required Python and CoolProp software to run my programm? I want to include these files, or codes in the app such that the other users don’t have to download Python and CoolProp separately. standalone app, app designer, matlab, python function, python, matlab compiler, compiler MATLAB Answers — New Questions
Solve F=ma for position. I need to solve 2nd order differential equation in MATLAB and I read all the tutorials out there I still can’t figure out how to do it, Please help!
I know I have F=ma=m*dv/dt=m*d^2x/dt^2 and I need first to solve for velocity by using ode23 once, then use ode23 again on whatever that answer is to solve for position, but I don’t know how to set it up in a code, please help!I know I have F=ma=m*dv/dt=m*d^2x/dt^2 and I need first to solve for velocity by using ode23 once, then use ode23 again on whatever that answer is to solve for position, but I don’t know how to set it up in a code, please help! I know I have F=ma=m*dv/dt=m*d^2x/dt^2 and I need first to solve for velocity by using ode23 once, then use ode23 again on whatever that answer is to solve for position, but I don’t know how to set it up in a code, please help! solve f=ma for position in matlab MATLAB Answers — New Questions
Can I transfer train “visionTransformer” to handle image sizes other than 384x384X3?
In the related Matlab doc, only change of "head" is described.In the related Matlab doc, only change of "head" is described. In the related Matlab doc, only change of "head" is described. visiontransformer, image size, grey images MATLAB Answers — New Questions
how to use Matlab netCDF functions for 4 dimensions data?
I have data with four dimensions, there are (lon,lat,level,time).
I have no idea what should I do with this kind of data..
this is the display of my data:
Variablename
Size: 249x249x34x2
Dimensions: west_east,south_north,bottom_top,Time
Datatype: single
Attributes:
FieldType = 104
MemoryOrder = ‘XYZ’
description = ‘pm10 dry mass’
units = ‘ug m^-3’
stagger = ”
coordinates = ‘XLONG XLAT’
% code
clc
clear
file = ‘F:…’;
data = double (ncread(file,’variablename’));
DATA = squeeze(data(:,:,1,1)); % I just think this command usable to 4D data (lon,lat,level,time), I don’t know for sure
DATA = log10(DATA);
% lattitude and longitude
lat = double(ncread(file,’XLAT’));
lon = double(ncread(file,’XLONG’));
xlat = lat(1,:,1);
xlon = lon(:,1,1);
[xlat,xlon] = meshgrid(xlat,xlon);
When I use ‘surfacem(xlat,xlon,DATA);’ with the codes that following above, my result it is not look good, the DATA only shown around the ocean (lat and lon).
please give me the suggestions the correct way to read 4D data and get the result from that kind of data..
I really need your help
Thank youI have data with four dimensions, there are (lon,lat,level,time).
I have no idea what should I do with this kind of data..
this is the display of my data:
Variablename
Size: 249x249x34x2
Dimensions: west_east,south_north,bottom_top,Time
Datatype: single
Attributes:
FieldType = 104
MemoryOrder = ‘XYZ’
description = ‘pm10 dry mass’
units = ‘ug m^-3’
stagger = ”
coordinates = ‘XLONG XLAT’
% code
clc
clear
file = ‘F:…’;
data = double (ncread(file,’variablename’));
DATA = squeeze(data(:,:,1,1)); % I just think this command usable to 4D data (lon,lat,level,time), I don’t know for sure
DATA = log10(DATA);
% lattitude and longitude
lat = double(ncread(file,’XLAT’));
lon = double(ncread(file,’XLONG’));
xlat = lat(1,:,1);
xlon = lon(:,1,1);
[xlat,xlon] = meshgrid(xlat,xlon);
When I use ‘surfacem(xlat,xlon,DATA);’ with the codes that following above, my result it is not look good, the DATA only shown around the ocean (lat and lon).
please give me the suggestions the correct way to read 4D data and get the result from that kind of data..
I really need your help
Thank you I have data with four dimensions, there are (lon,lat,level,time).
I have no idea what should I do with this kind of data..
this is the display of my data:
Variablename
Size: 249x249x34x2
Dimensions: west_east,south_north,bottom_top,Time
Datatype: single
Attributes:
FieldType = 104
MemoryOrder = ‘XYZ’
description = ‘pm10 dry mass’
units = ‘ug m^-3’
stagger = ”
coordinates = ‘XLONG XLAT’
% code
clc
clear
file = ‘F:…’;
data = double (ncread(file,’variablename’));
DATA = squeeze(data(:,:,1,1)); % I just think this command usable to 4D data (lon,lat,level,time), I don’t know for sure
DATA = log10(DATA);
% lattitude and longitude
lat = double(ncread(file,’XLAT’));
lon = double(ncread(file,’XLONG’));
xlat = lat(1,:,1);
xlon = lon(:,1,1);
[xlat,xlon] = meshgrid(xlat,xlon);
When I use ‘surfacem(xlat,xlon,DATA);’ with the codes that following above, my result it is not look good, the DATA only shown around the ocean (lat and lon).
please give me the suggestions the correct way to read 4D data and get the result from that kind of data..
I really need your help
Thank you netcdf, 4d datasets, surfacem MATLAB Answers — New Questions
Finding a a path between two points on a 3d surface that proceeds through lowest value points.
Hello,
I have data (100X50 array for X, Y and Z coordiantes ) corresponding to the surface shown in the below image. I am interested in obtaining paths from flat region (right side yellow circle) of the surface to the minima at red and brown cricle on the left side of the surface. Only condition is that the path should proceed through lowest value points along the Z axis. I could obtain one path connecting yellow and red circles by using "min" function in matlab. I tried find peaks in order to obtain the other path (shown with black arrow in the image). But, the well around the brown circle is very shallow resulting the findpeaks gives only one peak at the region of red circle. Could you please help me to obtain the second path that connects yellow and brown circles. I have also attached my data file. "Shortestpath" function in matlab might be useful for this purpose. I am however not sure how to use it.
These type of paths are referred as "minimum energy paths" in chemistry, assuming that the Z-axis is energy and X- and Y-axis represent molecular coordiantes. In other words, I am looking for a steepest descent path between yellow and brown circles.
Thank you very much for your time
Regards,
MaheshHello,
I have data (100X50 array for X, Y and Z coordiantes ) corresponding to the surface shown in the below image. I am interested in obtaining paths from flat region (right side yellow circle) of the surface to the minima at red and brown cricle on the left side of the surface. Only condition is that the path should proceed through lowest value points along the Z axis. I could obtain one path connecting yellow and red circles by using "min" function in matlab. I tried find peaks in order to obtain the other path (shown with black arrow in the image). But, the well around the brown circle is very shallow resulting the findpeaks gives only one peak at the region of red circle. Could you please help me to obtain the second path that connects yellow and brown circles. I have also attached my data file. "Shortestpath" function in matlab might be useful for this purpose. I am however not sure how to use it.
These type of paths are referred as "minimum energy paths" in chemistry, assuming that the Z-axis is energy and X- and Y-axis represent molecular coordiantes. In other words, I am looking for a steepest descent path between yellow and brown circles.
Thank you very much for your time
Regards,
Mahesh Hello,
I have data (100X50 array for X, Y and Z coordiantes ) corresponding to the surface shown in the below image. I am interested in obtaining paths from flat region (right side yellow circle) of the surface to the minima at red and brown cricle on the left side of the surface. Only condition is that the path should proceed through lowest value points along the Z axis. I could obtain one path connecting yellow and red circles by using "min" function in matlab. I tried find peaks in order to obtain the other path (shown with black arrow in the image). But, the well around the brown circle is very shallow resulting the findpeaks gives only one peak at the region of red circle. Could you please help me to obtain the second path that connects yellow and brown circles. I have also attached my data file. "Shortestpath" function in matlab might be useful for this purpose. I am however not sure how to use it.
These type of paths are referred as "minimum energy paths" in chemistry, assuming that the Z-axis is energy and X- and Y-axis represent molecular coordiantes. In other words, I am looking for a steepest descent path between yellow and brown circles.
Thank you very much for your time
Regards,
Mahesh minimum value path between two points on 3d grid MATLAB Answers — New Questions
Extract two floating point numbers from a string
This should be easy, but I have no experience with MATLAB regexp or pattern and can’t adapt the other answers about extracting numbers from a mixed string.
I want to get the latitude and longitude as floating point numbers from a string that looks like this:
23.047°S 67.782°W
The numbers will have 1-3 characters before the decimal point. An "S" or a "W" will produce a negative number.
Suggestions welcome.This should be easy, but I have no experience with MATLAB regexp or pattern and can’t adapt the other answers about extracting numbers from a mixed string.
I want to get the latitude and longitude as floating point numbers from a string that looks like this:
23.047°S 67.782°W
The numbers will have 1-3 characters before the decimal point. An "S" or a "W" will produce a negative number.
Suggestions welcome. This should be easy, but I have no experience with MATLAB regexp or pattern and can’t adapt the other answers about extracting numbers from a mixed string.
I want to get the latitude and longitude as floating point numbers from a string that looks like this:
23.047°S 67.782°W
The numbers will have 1-3 characters before the decimal point. An "S" or a "W" will produce a negative number.
Suggestions welcome. string MATLAB Answers — New Questions
When running the setup.exe file for MATLAB R2024A on a Windows system, the “Error code: -354” appears.
Unable to open the requested feature.Check your internet connection and proxy settings in MATLAB Web preferences and then try starting the feature again.
Detailed information:
Error code: -354
Error message: ERR_CONTENT_LENGTH_MISMATCHUnable to open the requested feature.Check your internet connection and proxy settings in MATLAB Web preferences and then try starting the feature again.
Detailed information:
Error code: -354
Error message: ERR_CONTENT_LENGTH_MISMATCH Unable to open the requested feature.Check your internet connection and proxy settings in MATLAB Web preferences and then try starting the feature again.
Detailed information:
Error code: -354
Error message: ERR_CONTENT_LENGTH_MISMATCH installation error MATLAB Answers — New Questions