Tag Archives: matlab
I have a MATLAB 2022 code that used the poly.intersect function–I can’t find in R2024 and need a workaround
I have a MATLAB 2022 code that used the poly.intersect function–I can’t find in R2024 and need a workaround to compute the intersection of polygons. The code is below. In line 12 the polyIntersect function is used:
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
How do I modify the code in lieu of using polyIntersect ?
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], ‘Simplify’, false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], ‘Simplify’, false);
inPolyNewsub = intersect(inPolyNew, hucSub,’KeepCollinearPoints’,true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder ‘outShapes_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, ‘VariableNames’, {‘outInt_acres1’ });
writetable(T, [dataFolder ‘outTables_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i)) ‘.txt’])
endI have a MATLAB 2022 code that used the poly.intersect function–I can’t find in R2024 and need a workaround to compute the intersection of polygons. The code is below. In line 12 the polyIntersect function is used:
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
How do I modify the code in lieu of using polyIntersect ?
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], ‘Simplify’, false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], ‘Simplify’, false);
inPolyNewsub = intersect(inPolyNew, hucSub,’KeepCollinearPoints’,true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder ‘outShapes_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, ‘VariableNames’, {‘outInt_acres1’ });
writetable(T, [dataFolder ‘outTables_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i)) ‘.txt’])
end I have a MATLAB 2022 code that used the poly.intersect function–I can’t find in R2024 and need a workaround to compute the intersection of polygons. The code is below. In line 12 the polyIntersect function is used:
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
How do I modify the code in lieu of using polyIntersect ?
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], ‘Simplify’, false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], ‘Simplify’, false);
inPolyNewsub = intersect(inPolyNew, hucSub,’KeepCollinearPoints’,true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder ‘outShapes_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, ‘VariableNames’, {‘outInt_acres1’ });
writetable(T, [dataFolder ‘outTables_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i)) ‘.txt’])
end poly.intersect MATLAB Answers — New Questions
How do I preallocate memory
I get the error message at the end of the first for loop (after code: OutData(ii).hucID = hucID;) that I should consider preallocating memory. How do I do that for the following code:
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], ‘Simplify’, false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], ‘Simplify’, false);
inPolyNewsub = intersect(inPolyNew, hucSub,’KeepCollinearPoints’,true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder ‘outShapes_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, ‘VariableNames’, {‘outInt_acres1’ });
writetable(T, [dataFolder ‘outTables_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i)) ‘.txt’])
end
endI get the error message at the end of the first for loop (after code: OutData(ii).hucID = hucID;) that I should consider preallocating memory. How do I do that for the following code:
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], ‘Simplify’, false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], ‘Simplify’, false);
inPolyNewsub = intersect(inPolyNew, hucSub,’KeepCollinearPoints’,true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder ‘outShapes_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, ‘VariableNames’, {‘outInt_acres1’ });
writetable(T, [dataFolder ‘outTables_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i)) ‘.txt’])
end
end I get the error message at the end of the first for loop (after code: OutData(ii).hucID = hucID;) that I should consider preallocating memory. How do I do that for the following code:
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], ‘Simplify’, false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], ‘Simplify’, false);
inPolyNewsub = intersect(inPolyNew, hucSub,’KeepCollinearPoints’,true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder ‘outShapes_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, ‘VariableNames’, {‘outInt_acres1’ });
writetable(T, [dataFolder ‘outTables_S’ hucID ‘_outInt_’ char(inFiles.NewShape(i)) ‘.txt’])
end
end preallocate memory MATLAB Answers — New Questions
I am using MATLAB 2015b and I dont need #include #include . How to remove these files from code
I am using MATLAB 2015b and I dont need #include <string.h> #include <stddef.h>. How to remove these files from codeI am using MATLAB 2015b and I dont need #include <string.h> #include <stddef.h>. How to remove these files from code I am using MATLAB 2015b and I dont need #include <string.h> #include <stddef.h>. How to remove these files from code #include string.h #include stddef.h MATLAB Answers — New Questions
Assigning correct symbols and colors to group scatterplot
Dear all, could you help me please on a group scatter plot?
I have three regions (MSD, DPG and WFS) and four seasons (Winter, Spring, Summer and Autumn). I chose four colors to represent the seasons, and 3 symbols to represent the regions, however, the function doesn’t understand this way. The symbols are correct to each region, but the colors are inconsistent, I think it is because there are 3 regions, but 4 seasons. The thing is, I need always the same color to the same season at each region/symbol, but I could not figure it out yet. Please, could you help me? The data is attached and the code below. Thank you very much in advance!
load gscat.mat
gscatter(x,y,g,’rkgb’,’o*h’,6,’on’,’Hind’,’Twin’)
legend(‘Location’,’northeastoutside’)Dear all, could you help me please on a group scatter plot?
I have three regions (MSD, DPG and WFS) and four seasons (Winter, Spring, Summer and Autumn). I chose four colors to represent the seasons, and 3 symbols to represent the regions, however, the function doesn’t understand this way. The symbols are correct to each region, but the colors are inconsistent, I think it is because there are 3 regions, but 4 seasons. The thing is, I need always the same color to the same season at each region/symbol, but I could not figure it out yet. Please, could you help me? The data is attached and the code below. Thank you very much in advance!
load gscat.mat
gscatter(x,y,g,’rkgb’,’o*h’,6,’on’,’Hind’,’Twin’)
legend(‘Location’,’northeastoutside’) Dear all, could you help me please on a group scatter plot?
I have three regions (MSD, DPG and WFS) and four seasons (Winter, Spring, Summer and Autumn). I chose four colors to represent the seasons, and 3 symbols to represent the regions, however, the function doesn’t understand this way. The symbols are correct to each region, but the colors are inconsistent, I think it is because there are 3 regions, but 4 seasons. The thing is, I need always the same color to the same season at each region/symbol, but I could not figure it out yet. Please, could you help me? The data is attached and the code below. Thank you very much in advance!
load gscat.mat
gscatter(x,y,g,’rkgb’,’o*h’,6,’on’,’Hind’,’Twin’)
legend(‘Location’,’northeastoutside’) gscatter, scatter plot MATLAB Answers — New Questions
Why it shows“Not all channels support on-demand operations. Only clocked operations are allowed”when I use NI-DAQ to acquire data?
Hi, all,
When I want to use MATLAB (R2022b-academic use) to control NI-USB 4431 to acquire data, the command window shows "Not all channels support on-demand operations. Only clocked operations are allowed." What does this mean? I can’t figure out how to solve it (I have installed NI-DAQmx toolbox, version 22.2.0). Here is the code:
dq = daq("ni");
dq.Rate = 8000;
ch1 = addinput(dq, d.DeviceID, "ai1", "Voltage");
tabledata = read(dq)
In addition, the NI-4431 device information is as follows.
ni: National Instruments(TM) USB-4431 (Device ID: ‘Dev1’)
Analog input supports:
-10 to +10 Volts range
Rates from 1000.0 to 102400.0 scansc
4 channels (‘ai0′,’ai1′,’ai2′,’ai3’)
‘Voltage’,’Accelerometer’,’Microphone’,’IEPE’ measurement types
Analog output supports:
-3.5 to +3.5 Volts range
Rates from 800.0 to 96000.0 scansc
1 channel (‘ao0’)
‘Voltage’ measurement type
Thanks!Hi, all,
When I want to use MATLAB (R2022b-academic use) to control NI-USB 4431 to acquire data, the command window shows "Not all channels support on-demand operations. Only clocked operations are allowed." What does this mean? I can’t figure out how to solve it (I have installed NI-DAQmx toolbox, version 22.2.0). Here is the code:
dq = daq("ni");
dq.Rate = 8000;
ch1 = addinput(dq, d.DeviceID, "ai1", "Voltage");
tabledata = read(dq)
In addition, the NI-4431 device information is as follows.
ni: National Instruments(TM) USB-4431 (Device ID: ‘Dev1’)
Analog input supports:
-10 to +10 Volts range
Rates from 1000.0 to 102400.0 scansc
4 channels (‘ai0′,’ai1′,’ai2′,’ai3’)
‘Voltage’,’Accelerometer’,’Microphone’,’IEPE’ measurement types
Analog output supports:
-3.5 to +3.5 Volts range
Rates from 800.0 to 96000.0 scansc
1 channel (‘ao0’)
‘Voltage’ measurement type
Thanks! Hi, all,
When I want to use MATLAB (R2022b-academic use) to control NI-USB 4431 to acquire data, the command window shows "Not all channels support on-demand operations. Only clocked operations are allowed." What does this mean? I can’t figure out how to solve it (I have installed NI-DAQmx toolbox, version 22.2.0). Here is the code:
dq = daq("ni");
dq.Rate = 8000;
ch1 = addinput(dq, d.DeviceID, "ai1", "Voltage");
tabledata = read(dq)
In addition, the NI-4431 device information is as follows.
ni: National Instruments(TM) USB-4431 (Device ID: ‘Dev1’)
Analog input supports:
-10 to +10 Volts range
Rates from 1000.0 to 102400.0 scansc
4 channels (‘ai0′,’ai1′,’ai2′,’ai3’)
‘Voltage’,’Accelerometer’,’Microphone’,’IEPE’ measurement types
Analog output supports:
-3.5 to +3.5 Volts range
Rates from 800.0 to 96000.0 scansc
1 channel (‘ao0’)
‘Voltage’ measurement type
Thanks! ni-daqmx, acquire data, addinput MATLAB Answers — New Questions
How to make directions bigger in current plot?
I am using the current command (https://es.mathworks.com/help/antenna/ref/cavity.current.html) to plot the current distribution of an antenna with the current direction. I want to include such a plot in my final project but the arrows that indicate the direction are too tiny to be seen in the figure. I am trying to configure the plot to make the lines thicker but I haven’t found how to do it.I am using the current command (https://es.mathworks.com/help/antenna/ref/cavity.current.html) to plot the current distribution of an antenna with the current direction. I want to include such a plot in my final project but the arrows that indicate the direction are too tiny to be seen in the figure. I am trying to configure the plot to make the lines thicker but I haven’t found how to do it. I am using the current command (https://es.mathworks.com/help/antenna/ref/cavity.current.html) to plot the current distribution of an antenna with the current direction. I want to include such a plot in my final project but the arrows that indicate the direction are too tiny to be seen in the figure. I am trying to configure the plot to make the lines thicker but I haven’t found how to do it. current, antennas, plot, quiver, plotting MATLAB Answers — New Questions
StackedPlot with separate events
I’d like to make a stacked plot with each plot showing different events (each plot’s own events only). How could I fix this code to show only the proper data’s corresponding events? (apologies for my clumsy coding)
%make timetable
times=[1, 2, 5]’;
s=seconds(times);
variable=[3, 4, 5]’;
T=table(s,variable);
TT=table2timetable(T);
%makes event table
EventTime = seconds(4);
lengths = seconds(1);
Events = eventtable(EventTime,EventLengths=lengths);
%Assign event table to time table
TT.Properties.Events=Events;
%make timetable
variable2=[6, 8, 9]’;
T2=table(s,variable2);
TT2=table2timetable(T2);
%makes event table
EventTime2 = seconds(1);
lengths2 = seconds(1);
Events2 = eventtable(EventTime2,EventLengths=lengths2);
%Assign event table2 to time table2
TT2.Properties.Events=Events2;
stackedplot(TT,TT2)I’d like to make a stacked plot with each plot showing different events (each plot’s own events only). How could I fix this code to show only the proper data’s corresponding events? (apologies for my clumsy coding)
%make timetable
times=[1, 2, 5]’;
s=seconds(times);
variable=[3, 4, 5]’;
T=table(s,variable);
TT=table2timetable(T);
%makes event table
EventTime = seconds(4);
lengths = seconds(1);
Events = eventtable(EventTime,EventLengths=lengths);
%Assign event table to time table
TT.Properties.Events=Events;
%make timetable
variable2=[6, 8, 9]’;
T2=table(s,variable2);
TT2=table2timetable(T2);
%makes event table
EventTime2 = seconds(1);
lengths2 = seconds(1);
Events2 = eventtable(EventTime2,EventLengths=lengths2);
%Assign event table2 to time table2
TT2.Properties.Events=Events2;
stackedplot(TT,TT2) I’d like to make a stacked plot with each plot showing different events (each plot’s own events only). How could I fix this code to show only the proper data’s corresponding events? (apologies for my clumsy coding)
%make timetable
times=[1, 2, 5]’;
s=seconds(times);
variable=[3, 4, 5]’;
T=table(s,variable);
TT=table2timetable(T);
%makes event table
EventTime = seconds(4);
lengths = seconds(1);
Events = eventtable(EventTime,EventLengths=lengths);
%Assign event table to time table
TT.Properties.Events=Events;
%make timetable
variable2=[6, 8, 9]’;
T2=table(s,variable2);
TT2=table2timetable(T2);
%makes event table
EventTime2 = seconds(1);
lengths2 = seconds(1);
Events2 = eventtable(EventTime2,EventLengths=lengths2);
%Assign event table2 to time table2
TT2.Properties.Events=Events2;
stackedplot(TT,TT2) stackedplot, plotting MATLAB Answers — New Questions
App Designer and Simulink Interchange
Hi, i know it sounds a bit crazy but I want to interact between app designer and simulink.
I am working with Arduino Due, and I reahced where too many blocks in Simulink is causing some issue.
Now my approach is to read the CAN via Simulink and read that live CAN message then manipulate it within App designer.
Also, use App designer to manipulate the Arduino’s I/Os.
The problem I am having is once the Simulink is connected to Arduino, I do not see any options that I can work with the Arduino’s I/Os. Unless I have the Arduino blocks within the simlink that has constant block to it which can be manipulate within app designer. However, this case will not reduece the Simulink information that embedded to the Arduino.
Any ideas where I can reduce the Simulink and somehow work with Arduino at the same time?
I tried to read the CAN message via app designer, it crashed (this would be the ideal option but some reason it isn’t working for me 🙁
Thanks!Hi, i know it sounds a bit crazy but I want to interact between app designer and simulink.
I am working with Arduino Due, and I reahced where too many blocks in Simulink is causing some issue.
Now my approach is to read the CAN via Simulink and read that live CAN message then manipulate it within App designer.
Also, use App designer to manipulate the Arduino’s I/Os.
The problem I am having is once the Simulink is connected to Arduino, I do not see any options that I can work with the Arduino’s I/Os. Unless I have the Arduino blocks within the simlink that has constant block to it which can be manipulate within app designer. However, this case will not reduece the Simulink information that embedded to the Arduino.
Any ideas where I can reduce the Simulink and somehow work with Arduino at the same time?
I tried to read the CAN message via app designer, it crashed (this would be the ideal option but some reason it isn’t working for me 🙁
Thanks! Hi, i know it sounds a bit crazy but I want to interact between app designer and simulink.
I am working with Arduino Due, and I reahced where too many blocks in Simulink is causing some issue.
Now my approach is to read the CAN via Simulink and read that live CAN message then manipulate it within App designer.
Also, use App designer to manipulate the Arduino’s I/Os.
The problem I am having is once the Simulink is connected to Arduino, I do not see any options that I can work with the Arduino’s I/Os. Unless I have the Arduino blocks within the simlink that has constant block to it which can be manipulate within app designer. However, this case will not reduece the Simulink information that embedded to the Arduino.
Any ideas where I can reduce the Simulink and somehow work with Arduino at the same time?
I tried to read the CAN message via app designer, it crashed (this would be the ideal option but some reason it isn’t working for me 🙁
Thanks! arduino, appdesigner, simulink, canbus MATLAB Answers — New Questions
Plotting path of rods on a circular disk along a surface to deduce rack gear profile.
I am trying to design a custom rack gear similar to ones used in a rack and pinion gear system. Instead of a pinion i am using a disk with 4 rods equally spaced on the disk that almost act as the teeth. I want to be able to plot the path of the rods as the disk rotates over a flat surface by simulating the movement. With this path I can design the rack.I am trying to design a custom rack gear similar to ones used in a rack and pinion gear system. Instead of a pinion i am using a disk with 4 rods equally spaced on the disk that almost act as the teeth. I want to be able to plot the path of the rods as the disk rotates over a flat surface by simulating the movement. With this path I can design the rack. I am trying to design a custom rack gear similar to ones used in a rack and pinion gear system. Instead of a pinion i am using a disk with 4 rods equally spaced on the disk that almost act as the teeth. I want to be able to plot the path of the rods as the disk rotates over a flat surface by simulating the movement. With this path I can design the rack. path simulation, location plot, gears MATLAB Answers — New Questions
There was an error loading the library
Dear all,
I put the compiled dll file (written in C) in ‘C:Program FilesMATLABR2011bexterninclude
I have a problem when I tried to load the library using the following command:
hfile = [matlabroot ‘externincludedllspinapi.h’];
loadlibrary(‘spinapi’, hfile)
it gave me the following error message:
Error using loadlibrary (line 421)
There was an error loading the library "spinapi"
The specified module could not be found.
Caused by:
Error using loaddefinedlibrary
The specified module could not be found.
My operating system is 64bit Win7, matlab is 64bit version, compiler is Microsoft Software Development Kit (SDK) 7.1, which is recommended in http://www.mathworks.com/support/compilers/R2011b/win64.html
Does anyone know what the problem is? I almost tried every method that I could find in google. But they didn’t help. I am so deperated……
One thing made me very confused was that, I did exactly the same in my old computer, its operating system is 32bit Windows XP, matlab is R2009a 32bit version, compiler is lcc-win32 C, and it could load the library without any error!!!
I will be very thankful to anyone who can help me.
Best Regards,
KitDear all,
I put the compiled dll file (written in C) in ‘C:Program FilesMATLABR2011bexterninclude
I have a problem when I tried to load the library using the following command:
hfile = [matlabroot ‘externincludedllspinapi.h’];
loadlibrary(‘spinapi’, hfile)
it gave me the following error message:
Error using loadlibrary (line 421)
There was an error loading the library "spinapi"
The specified module could not be found.
Caused by:
Error using loaddefinedlibrary
The specified module could not be found.
My operating system is 64bit Win7, matlab is 64bit version, compiler is Microsoft Software Development Kit (SDK) 7.1, which is recommended in http://www.mathworks.com/support/compilers/R2011b/win64.html
Does anyone know what the problem is? I almost tried every method that I could find in google. But they didn’t help. I am so deperated……
One thing made me very confused was that, I did exactly the same in my old computer, its operating system is 32bit Windows XP, matlab is R2009a 32bit version, compiler is lcc-win32 C, and it could load the library without any error!!!
I will be very thankful to anyone who can help me.
Best Regards,
Kit Dear all,
I put the compiled dll file (written in C) in ‘C:Program FilesMATLABR2011bexterninclude
I have a problem when I tried to load the library using the following command:
hfile = [matlabroot ‘externincludedllspinapi.h’];
loadlibrary(‘spinapi’, hfile)
it gave me the following error message:
Error using loadlibrary (line 421)
There was an error loading the library "spinapi"
The specified module could not be found.
Caused by:
Error using loaddefinedlibrary
The specified module could not be found.
My operating system is 64bit Win7, matlab is 64bit version, compiler is Microsoft Software Development Kit (SDK) 7.1, which is recommended in http://www.mathworks.com/support/compilers/R2011b/win64.html
Does anyone know what the problem is? I almost tried every method that I could find in google. But they didn’t help. I am so deperated……
One thing made me very confused was that, I did exactly the same in my old computer, its operating system is 32bit Windows XP, matlab is R2009a 32bit version, compiler is lcc-win32 C, and it could load the library without any error!!!
I will be very thankful to anyone who can help me.
Best Regards,
Kit loading the library, specified module could not be found MATLAB Answers — New Questions
Error “Method ‘Control’ is not defined for class ‘matlab.graphics.controls.internal.Control'”
fig = figure(‘Name’, ‘test’);
t = tiledlayout(fig, 4, 4);
The latest instruction throw this strange error on one of my PC (the other one works fine)
Method ‘Control’ is not defined for class ‘matlab.graphics.controls.internal.Control’ or is removed from MATLAB’s search path.
Error in matlab.graphics.shape.internal.Button
Error in matlab.graphics.controls.internal.PostUpdatePlugin.doCacheLoad
Error in matlab.graphics.controls.internal.PostUpdatePlugin>@()matlab.graphics.controls.internal.PostUpdatePlugin.doCacheLoad(canvasParent)
Does anyone what is that about?fig = figure(‘Name’, ‘test’);
t = tiledlayout(fig, 4, 4);
The latest instruction throw this strange error on one of my PC (the other one works fine)
Method ‘Control’ is not defined for class ‘matlab.graphics.controls.internal.Control’ or is removed from MATLAB’s search path.
Error in matlab.graphics.shape.internal.Button
Error in matlab.graphics.controls.internal.PostUpdatePlugin.doCacheLoad
Error in matlab.graphics.controls.internal.PostUpdatePlugin>@()matlab.graphics.controls.internal.PostUpdatePlugin.doCacheLoad(canvasParent)
Does anyone what is that about? fig = figure(‘Name’, ‘test’);
t = tiledlayout(fig, 4, 4);
The latest instruction throw this strange error on one of my PC (the other one works fine)
Method ‘Control’ is not defined for class ‘matlab.graphics.controls.internal.Control’ or is removed from MATLAB’s search path.
Error in matlab.graphics.shape.internal.Button
Error in matlab.graphics.controls.internal.PostUpdatePlugin.doCacheLoad
Error in matlab.graphics.controls.internal.PostUpdatePlugin>@()matlab.graphics.controls.internal.PostUpdatePlugin.doCacheLoad(canvasParent)
Does anyone what is that about? tiledlayout, error MATLAB Answers — New Questions
MCC DaqHat and Raspberry Pi Guidance
We are in the process of building a data acquisitoin system using a remote Raspberry Pi, and 2 Daqhats from MCC-DAQ. I am wondering if anyone else has tried this configuration and if so is there any guidance that they would recommend?
-Matlab says that they don’t support these modules. I was pretty sure when we purchased it they acted like they did. I have been unable to find any reference to this within Mathlab or the Forums.
-MCC-DAQ acted like it was fairly straightforward. However, since starting this they have made it very difficult to communicate with them. I have not really found any material there either yet.
I apologize for this being a vague post but I don’t have many details to share yet.
Sincerely, PaulWe are in the process of building a data acquisitoin system using a remote Raspberry Pi, and 2 Daqhats from MCC-DAQ. I am wondering if anyone else has tried this configuration and if so is there any guidance that they would recommend?
-Matlab says that they don’t support these modules. I was pretty sure when we purchased it they acted like they did. I have been unable to find any reference to this within Mathlab or the Forums.
-MCC-DAQ acted like it was fairly straightforward. However, since starting this they have made it very difficult to communicate with them. I have not really found any material there either yet.
I apologize for this being a vague post but I don’t have many details to share yet.
Sincerely, Paul We are in the process of building a data acquisitoin system using a remote Raspberry Pi, and 2 Daqhats from MCC-DAQ. I am wondering if anyone else has tried this configuration and if so is there any guidance that they would recommend?
-Matlab says that they don’t support these modules. I was pretty sure when we purchased it they acted like they did. I have been unable to find any reference to this within Mathlab or the Forums.
-MCC-DAQ acted like it was fairly straightforward. However, since starting this they have made it very difficult to communicate with them. I have not really found any material there either yet.
I apologize for this being a vague post but I don’t have many details to share yet.
Sincerely, Paul raspberry pi, daqhat MATLAB Answers — New Questions
Simscape multibody: How to simulate a cylinder rolling down an irregular surface
Hello to all,
I am a beginner to using simulink and I am trying to use simscape to model a cylinder rolling down an irregularly shaped incline. I used the documentation on how to model a wheel rolling down a straight incline to make my model (https://nl.mathworks.com/help/sm/ug/model-a-rolling-wheel.html) but I replaced the brick solid with a custom file.
Model in the custom file:
When I simulate the cylinder it does not behave like I would expect with the cylinder sort of "hovering" over the concave areas whilst flailing and drifting around.
From what I have read, it seems this has to do with the convex hull representation of the object that the contact force block uses. However, I am not sure how to fix this. Is there any way of specifying the block not to use convex hull? Or how could I go about fixing this model?
Any help is appreciated :)Hello to all,
I am a beginner to using simulink and I am trying to use simscape to model a cylinder rolling down an irregularly shaped incline. I used the documentation on how to model a wheel rolling down a straight incline to make my model (https://nl.mathworks.com/help/sm/ug/model-a-rolling-wheel.html) but I replaced the brick solid with a custom file.
Model in the custom file:
When I simulate the cylinder it does not behave like I would expect with the cylinder sort of "hovering" over the concave areas whilst flailing and drifting around.
From what I have read, it seems this has to do with the convex hull representation of the object that the contact force block uses. However, I am not sure how to fix this. Is there any way of specifying the block not to use convex hull? Or how could I go about fixing this model?
Any help is appreciated 🙂 Hello to all,
I am a beginner to using simulink and I am trying to use simscape to model a cylinder rolling down an irregularly shaped incline. I used the documentation on how to model a wheel rolling down a straight incline to make my model (https://nl.mathworks.com/help/sm/ug/model-a-rolling-wheel.html) but I replaced the brick solid with a custom file.
Model in the custom file:
When I simulate the cylinder it does not behave like I would expect with the cylinder sort of "hovering" over the concave areas whilst flailing and drifting around.
From what I have read, it seems this has to do with the convex hull representation of the object that the contact force block uses. However, I am not sure how to fix this. Is there any way of specifying the block not to use convex hull? Or how could I go about fixing this model?
Any help is appreciated 🙂 simscape, roll, simulink MATLAB Answers — New Questions
Test Exceptions and Mask Contraints within the TestManager
Hi,
i want to test my module under test using a test harness and testmanager combined with a test assesment. Additional to "normal" test cases, i also want to do out of range tests, or invalid mask inputs (contraints protected) or setting unvalid inputs for signals.
I found the openExample(‘matlab/VerifyErrorTestInputValidationOfAFunctionExample’) example, which is kind of what i want to do, but i want to integrate it into my test manager to automatically run several different tests.
An example, I do have a simulink subsystem, which has a mask parameter called a, which needs to be a postive number and is protected by a mask constraint. In my first test step i enter value 5 for this mask, in the next test i want to add a -5. I do expect the mask contraint exception to be thworn and it will be thrown but i want to add this expected exception to my test manager as a valid test that has passed when the correct exception has happened.
How can i do that?Hi,
i want to test my module under test using a test harness and testmanager combined with a test assesment. Additional to "normal" test cases, i also want to do out of range tests, or invalid mask inputs (contraints protected) or setting unvalid inputs for signals.
I found the openExample(‘matlab/VerifyErrorTestInputValidationOfAFunctionExample’) example, which is kind of what i want to do, but i want to integrate it into my test manager to automatically run several different tests.
An example, I do have a simulink subsystem, which has a mask parameter called a, which needs to be a postive number and is protected by a mask constraint. In my first test step i enter value 5 for this mask, in the next test i want to add a -5. I do expect the mask contraint exception to be thworn and it will be thrown but i want to add this expected exception to my test manager as a valid test that has passed when the correct exception has happened.
How can i do that? Hi,
i want to test my module under test using a test harness and testmanager combined with a test assesment. Additional to "normal" test cases, i also want to do out of range tests, or invalid mask inputs (contraints protected) or setting unvalid inputs for signals.
I found the openExample(‘matlab/VerifyErrorTestInputValidationOfAFunctionExample’) example, which is kind of what i want to do, but i want to integrate it into my test manager to automatically run several different tests.
An example, I do have a simulink subsystem, which has a mask parameter called a, which needs to be a postive number and is protected by a mask constraint. In my first test step i enter value 5 for this mask, in the next test i want to add a -5. I do expect the mask contraint exception to be thworn and it will be thrown but i want to add this expected exception to my test manager as a valid test that has passed when the correct exception has happened.
How can i do that? testmanager simulink exception outofrange mask MATLAB Answers — New Questions
Download of Matlab software.
I want to download the matlab software, but I am unable to verify my university, since I am directed to another university’s portal. Kindly help-guide me.I want to download the matlab software, but I am unable to verify my university, since I am directed to another university’s portal. Kindly help-guide me. I want to download the matlab software, but I am unable to verify my university, since I am directed to another university’s portal. Kindly help-guide me. – MATLAB Answers — New Questions
Speeding up updateOccupancy() function
I am trying to write a Mapping module where I ingest LIDAR data from a simulated sensor and create a 2D occupancy map using the Update2DMap function:
function [map] = Update2DMap(map, pose, points, hitProbUpdate, passProbUpdate)
% The map is then updated based on the where the ray intersects the
% world
tic
sensorPos = [pose(1) pose(2)];
for i = 1 : size(points, 1)
point = points(i,:);
% Calculate points which a LIDAR ray passes through and the end
% point
[endPoints, midPoints] = raycast(map, sensorPos, point);
% Update the points in the map where the ray has passed through as
% unoccupied therefore reduce their occupancy value
updateOccupancy(map, midPoints, passProbUpdate, ‘grid’);
% End point indicates it has hit an obstacle therefore the
% occupancy values should increase
updateOccupancy(map, endPoints, hitProbUpdate, ‘grid’);
end
toc % Currently takes ~3 seconds to complete this loop
end
Where:
map – 2D occupancy map being updated
pose – pose vector (x, y, theta)
points – n x 2 position vector
hitProbUpdate – probabilty change when an obstacle is detected
passProbUpdate – probabilty change when an obstacle is not detected
I am currently processing a position vector which dimensins ~9000 x 3 and this function is my bottleneck where the tic/toc pair show to complete the for-loop takes around 2-3 seconds which is very slow when plotting.
I’ve tried using parfor loops and seeing if there are ways to use my GPU but neither produces any significant speed increase.
I’m relatively new to using the Navigation/Mapping Toolbox so I wanted to reach out to the community in case anyone has advice on how to speed up my updating function.
Many thanks!I am trying to write a Mapping module where I ingest LIDAR data from a simulated sensor and create a 2D occupancy map using the Update2DMap function:
function [map] = Update2DMap(map, pose, points, hitProbUpdate, passProbUpdate)
% The map is then updated based on the where the ray intersects the
% world
tic
sensorPos = [pose(1) pose(2)];
for i = 1 : size(points, 1)
point = points(i,:);
% Calculate points which a LIDAR ray passes through and the end
% point
[endPoints, midPoints] = raycast(map, sensorPos, point);
% Update the points in the map where the ray has passed through as
% unoccupied therefore reduce their occupancy value
updateOccupancy(map, midPoints, passProbUpdate, ‘grid’);
% End point indicates it has hit an obstacle therefore the
% occupancy values should increase
updateOccupancy(map, endPoints, hitProbUpdate, ‘grid’);
end
toc % Currently takes ~3 seconds to complete this loop
end
Where:
map – 2D occupancy map being updated
pose – pose vector (x, y, theta)
points – n x 2 position vector
hitProbUpdate – probabilty change when an obstacle is detected
passProbUpdate – probabilty change when an obstacle is not detected
I am currently processing a position vector which dimensins ~9000 x 3 and this function is my bottleneck where the tic/toc pair show to complete the for-loop takes around 2-3 seconds which is very slow when plotting.
I’ve tried using parfor loops and seeing if there are ways to use my GPU but neither produces any significant speed increase.
I’m relatively new to using the Navigation/Mapping Toolbox so I wanted to reach out to the community in case anyone has advice on how to speed up my updating function.
Many thanks! I am trying to write a Mapping module where I ingest LIDAR data from a simulated sensor and create a 2D occupancy map using the Update2DMap function:
function [map] = Update2DMap(map, pose, points, hitProbUpdate, passProbUpdate)
% The map is then updated based on the where the ray intersects the
% world
tic
sensorPos = [pose(1) pose(2)];
for i = 1 : size(points, 1)
point = points(i,:);
% Calculate points which a LIDAR ray passes through and the end
% point
[endPoints, midPoints] = raycast(map, sensorPos, point);
% Update the points in the map where the ray has passed through as
% unoccupied therefore reduce their occupancy value
updateOccupancy(map, midPoints, passProbUpdate, ‘grid’);
% End point indicates it has hit an obstacle therefore the
% occupancy values should increase
updateOccupancy(map, endPoints, hitProbUpdate, ‘grid’);
end
toc % Currently takes ~3 seconds to complete this loop
end
Where:
map – 2D occupancy map being updated
pose – pose vector (x, y, theta)
points – n x 2 position vector
hitProbUpdate – probabilty change when an obstacle is detected
passProbUpdate – probabilty change when an obstacle is not detected
I am currently processing a position vector which dimensins ~9000 x 3 and this function is my bottleneck where the tic/toc pair show to complete the for-loop takes around 2-3 seconds which is very slow when plotting.
I’ve tried using parfor loops and seeing if there are ways to use my GPU but neither produces any significant speed increase.
I’m relatively new to using the Navigation/Mapping Toolbox so I wanted to reach out to the community in case anyone has advice on how to speed up my updating function.
Many thanks! mapping, lidar, occupancy, speed MATLAB Answers — New Questions
what is subplot and how to use it?
i want to plot two graphs in one single window then how to do so?
what is block? also give some hint on how join various elements and blocks while using simulink?i want to plot two graphs in one single window then how to do so?
what is block? also give some hint on how join various elements and blocks while using simulink? i want to plot two graphs in one single window then how to do so?
what is block? also give some hint on how join various elements and blocks while using simulink? plot, subplot, layout for subplot explained MATLAB Answers — New Questions
Encountered an inability to add error when using the modified UNet structure for prediction.
I am trying to add a ViT module to the UNet constructed by the updated unet3d in MATLAB r2024a, and everything is normal during the training process. I have verified the performance of the model after a certain period of time. The analyzeNetwork function shows no errors, and the size of the front and back connections is 65 * 1024 * 1 (SCB). This is the result of serializing the image.
Incorrect use of dlnetwork/predict (line 658)
Execution failed during layer ‘Transformer PositionEmbedding, Encoder Stage-4 Add-1’.
Error Unet3dTrain (line 288)
PredictedLabel=predict (net, image);
Reason:
Incorrect use of matlab. internal. path. cnn MLFusedNetwork/forwardExampleInputs
Arrays are not compatible for addition
Problem seems to occur when add the vector before position embedding and after position embedding.
There are no issues with adding custom print input size layers before and after this layer.
Here is part of the structure of the network.
My native language is not English, and I am using translation software. Please forgive any errors. The following is the code, which includes non English comments.
Code:
clc; clear;
rng(1);
% ========== 数据读取和数据集创建阶段 ==========
% 指定图像和标签文件的位置
imageDir = ‘X:BaiduDownloadbrats2021ProcessedData’;
labelDir = ‘X:BaiduDownloadbrats2021ProcessedData’; % 标签数据存储在同一位置
% 定义类别名和对应的标签ID
categories = ["background", "necrotic_tumor_core", "peritumoral_edema", "enhancing_tumor"]; % 有4类
labelIDs = [0, 1, 2, 4]; % 分别对应上述类别
% 假定输入数据为 128×128 的体积,有一个背景类和一个肿瘤类
inputSize = [128 128 8 2]; % 最后一个维度1表示1种不同的模态
numClasses = 4; % 类别数(背景和肿瘤)
% 创建图像和标签的数据存储
imds = imageDatastore(imageDir, ‘FileExtensions’,’.mat’, ‘ReadFcn’, @customReadData);
pxds = pixelLabelDatastore(labelDir, categories, labelIDs, ‘FileExtensions’,’.mat’, ‘ReadFcn’, @customReadLabels);
% 分割训练集和验证集
numFiles = numel(imds.Files);
idx = randperm(numFiles); % 随机打乱索引
% numFiles = round(0.001 * numFiles); % 选取小数据集测试
numTrain = round(0.9 * numFiles); % 假设80%的数据用于训练
% 使用索引分割数据
trainImds = subset(imds, idx(1:numTrain));
trainPxds = subset(pxds, idx(1:numTrain));
valImds = subset(imds, idx(numTrain+1:end));
valPxds = subset(pxds, idx(numTrain+1:end));
% 组合训练和验证数据
dsTrain = combine(trainImds, trainPxds);
dsVal = combine(valImds, valPxds);
% 补充函数
function labels = customReadLabels(filename)
fileContent = load(filename);
segmentation = fileContent.segmentation(:,:,74:81);
% 假设原始大小为240×240,计算裁剪偏移
cropSize = 200;
startCrop = (size(segmentation,1) – cropSize) / 2 + 1;
endCrop = startCrop + cropSize – 1;
% 四周均匀裁剪为160×160
croppedSegmentation = segmentation(startCrop:endCrop, startCrop:endCrop, :);
% 重置三维数据大小到128×128,使用最近邻插值方法
segmentationResized = imresize3(croppedSegmentation, [128, 128, size(croppedSegmentation, 3)], ‘Method’, ‘nearest’);
% 创建分类数据,确保使用正确的类别名
labels = categorical(segmentationResized, [0, 1, 2, 4], {‘background’, ‘necrotic_tumor_core’, ‘peritumoral_edema’, ‘enhancing_tumor’});
end
function data = customReadData(filename)
fileContent = load(filename);
% 提取特定切片
originalData = squeeze(fileContent.combinedData(:,:,74:81,[1, 3]));
% 同样计算裁剪偏移
cropSize = 200;
startCrop = (size(originalData,1) – cropSize) / 2 + 1;
endCrop = startCrop + cropSize – 1;
% 四周均匀裁剪为160×160
croppedData = originalData(startCrop:endCrop, startCrop:endCrop, :, :);
% 初始化一个新的四维数组,用于存储调整后的数据
resizedData = zeros(128, 128, size(croppedData, 3), size(croppedData, 4));
% 循环处理每一个通道
for i = 1:size(croppedData, 4)
% 调整每个通道的数据大小并进行灰度化
resizedData(:,:,:,i) = imresize3(mat2gray(croppedData(:,:,:,i)), [128, 128, size(croppedData, 3)]);
end
% 输出处理后的数据
data = resizedData;
end
% 创建3D U-Net网络
net = unet3d(inputSize, numClasses, Encoderdepth = 3);
% ========== Unet网络改造阶段 ==========
% 改造ResBlock
% 对Stage-1进行的操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer = convolution3dLayer([1, 1, 1], 64, ‘Name’, ‘Encoder-Stage-1-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-1-BN-Ident-1’);
addLayer = additionLayer(2, ‘Name’, ‘Encoder-Stage-1-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer);
net = addLayers(net, adjustBnLayer);
net = addLayers(net, addLayer);
% 连接新层
net = connectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-1-Conv-Ident-1’, ‘Encoder-Stage-1-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-1-BN-2′, ‘Encoder-Stage-1-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-1-BN-2’, ‘Encoder-Stage-1-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-1-BN-Ident-1’, ‘Encoder-Stage-1-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-1-Add-1’, ‘Encoder-Stage-1-ReLU-2’);
% 对Stage-2进行的操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer2 = convolution3dLayer([1, 1, 1], 128, ‘Name’, ‘Encoder-Stage-2-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer2 = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-2-BN-Ident-1’);
addLayer2 = additionLayer(2, ‘Name’, ‘Encoder-Stage-2-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer2);
net = addLayers(net, adjustBnLayer2);
net = addLayers(net, addLayer2);
% 连接新层
net = connectLayers(net, ‘Encoder-Stage-1-MaxPool’, ‘Encoder-Stage-2-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-2-Conv-Ident-1’, ‘Encoder-Stage-2-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-2-BN-2′, ‘Encoder-Stage-2-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-2-BN-2’, ‘Encoder-Stage-2-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-2-BN-Ident-1’, ‘Encoder-Stage-2-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-2-Add-1’, ‘Encoder-Stage-2-ReLU-2’);
% 对Stage-3进行操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer3 = convolution3dLayer([1, 1, 1], 256, ‘Name’, ‘Encoder-Stage-3-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer3 = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-3-BN-Ident-1’);
addLayer3 = additionLayer(2, ‘Name’, ‘Encoder-Stage-3-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer3);
net = addLayers(net, adjustBnLayer3);
net = addLayers(net, addLayer3);
% 连接新层
net = connectLayers(net, ‘Encoder-Stage-2-MaxPool’, ‘Encoder-Stage-3-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-3-Conv-Ident-1’, ‘Encoder-Stage-3-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-3-BN-2′, ‘Encoder-Stage-3-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-3-BN-2’, ‘Encoder-Stage-3-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-3-BN-Ident-1’, ‘Encoder-Stage-3-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-3-Add-1’, ‘Encoder-Stage-3-ReLU-2’);
% BatchNormalization改造为GroupNormalization
% 获取网络中所有层的名称
layerNames = {net.Layers.Name};
% 循环遍历所有层的名称,寻找匹配“BN”的层
for i = 1:length(layerNames)
if contains(layerNames{i}, ‘BN’)
% 创建新的组归一化层
gnLayer = groupNormalizationLayer(4, ‘Name’, layerNames{i});
% 替换现有的 BN 层
net = replaceLayer(net, layerNames{i}, gnLayer);
end
end
% 添加Vision Transformer Layer
PatchEmbeddingLayer1 = patchEmbeddingLayer([4 4 2], 1024, ‘Name’, ‘Transformer-PatchEmbedding’);
EmbeddingConcatenationLayer1 = embeddingConcatenationLayer(‘Name’, ‘Transformer-EmbeddingConcatenation’);
PositionEmbeddingLayer1 = positionEmbeddingLayer(1024, 1024, ‘Name’, ‘Transformer-PositionEmbedding’);
addLayer4 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-1’);
addLayer5 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-2’);
addLayer6 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-3’);
dropoutLayer1 = dropoutLayer(0.1, ‘Name’, ‘Transformer-DropOut-1’);
dropoutLayer2 = dropoutLayer(0.1, ‘Name’, ‘Transformer-DropOut-2’);
LayerNormalizationLayer1 = layerNormalizationLayer(‘Name’,’Transformer-LN-1′);
LayerNormalizationLayer2 = layerNormalizationLayer(‘Name’,’Transformer-LN-2′);
SelfAttentionLayer = selfAttentionLayer(8, 32, ‘Name’, ‘Transformer-SelfAttention’);
FullyConnectedLayer = fullyConnectedLayer(1024, ‘Name’, ‘Transformer-fc’);
ReshapeLayer = reshapeLayer(‘Transformer-reshape’);
index1dLayer = indexing1dLayer(‘Name’, ‘Transformer-index1d’);
% printShapeLayer1 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer1’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
% printShapeLayer2 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer2’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
% printShapeLayer3 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer3’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
net = addLayers(net, PatchEmbeddingLayer1);
net = addLayers(net, EmbeddingConcatenationLayer1);
net = addLayers(net, PositionEmbeddingLayer1);
net = addLayers(net, addLayer4);
net = addLayers(net, addLayer5);
net = addLayers(net, addLayer6);
net = addLayers(net, dropoutLayer1);
net = addLayers(net, dropoutLayer2);
net = addLayers(net, LayerNormalizationLayer1);
net = addLayers(net, LayerNormalizationLayer2);
net = addLayers(net, SelfAttentionLayer);
net = addLayers(net, FullyConnectedLayer);
net = addLayers(net, ReshapeLayer);
net = addLayers(net, index1dLayer);
% net = addLayers(net, printShapeLayer1);
% net = addLayers(net, printShapeLayer2);
% net = addLayers(net, printShapeLayer3);
% net = disconnectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-Conv-1’);
% net = disconnectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-BN-Ident-1’);
% net = connectLayers(net, ‘encoderImageInputLayer’, ‘printShapeLayer3’);
% net = connectLayers(net, ‘printShapeLayer3’, ‘Encoder-Stage-1-Conv-1’);
% net = connectLayers(net, ‘printShapeLayer3’, ‘Encoder-Stage-1-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-3-DropOut’, ‘Encoder-Stage-3-MaxPool’);
% net = connectLayers(net,’Encoder-Stage-3-ReLU-2′, ‘printShapeLayer1’);
% net = connectLayers(net,’printShapeLayer1′, ‘Transformer-PatchEmbedding’);
net = connectLayers(net,’Encoder-Stage-3-DropOut’, ‘Transformer-PatchEmbedding’);
net = connectLayers(net, ‘Transformer-PatchEmbedding’, ‘Transformer-EmbeddingConcatenation’);
net = connectLayers(net, ‘Transformer-EmbeddingConcatenation’, ‘Transformer-PositionEmbedding’);
net = connectLayers(net, ‘Transformer-PositionEmbedding’, ‘Encoder-Stage-4-Add-1/in1’);
net = connectLayers(net, ‘Transformer-EmbeddingConcatenation’, ‘Encoder-Stage-4-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-1’, ‘Transformer-DropOut-1’);
net = connectLayers(net, ‘Transformer-DropOut-1’, ‘Transformer-LN-1’);
net = connectLayers(net, ‘Transformer-LN-1’, ‘Transformer-SelfAttention’);
net = connectLayers(net, ‘Transformer-SelfAttention’, ‘Transformer-DropOut-2’);
net = connectLayers(net, ‘Transformer-DropOut-2’, ‘Encoder-Stage-4-Add-2/in1’);
net = connectLayers(net, ‘Transformer-DropOut-1’, ‘Encoder-Stage-4-Add-2/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-2’, ‘Transformer-LN-2’);
net = connectLayers(net, ‘Transformer-LN-2’, ‘Transformer-index1d’);
net = connectLayers(net, ‘Transformer-index1d’, ‘Transformer-fc’);
net = connectLayers(net, ‘Transformer-fc’, ‘Encoder-Stage-4-Add-3/in1’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-2’, ‘Encoder-Stage-4-Add-3/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-3’, ‘Transformer-reshape’);
% net = connectLayers(net, ‘Transformer-reshape’, ‘Encoder-Stage-3-DropOut’);
net = connectLayers(net, ‘Transformer-reshape’, ‘Encoder-Stage-3-MaxPool’);
% net = connectLayers(net, ‘Transformer-reshape’, ‘encoderDecoderSkipConnectionCrop3/in’);
% net = disconnectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘LatentNetwork-Bridge-Conv-1’);
% net = connectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘printShapeLayer2’);
net = removeLayers(net, ‘Encoder-Stage-3-MaxPool’);
net = connectLayers(net, ‘Transformer-reshape’, ‘LatentNetwork-Bridge-Conv-1’);
% net = connectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘LatentNetwork-Bridge-Conv-1’);
% 添加Attention Gate
relulayer1 = reluLayer(‘Name’, ‘AttentionGate-Stage-1-relu’);
relulayer2 = reluLayer(‘Name’, ‘AttentionGate-Stage-2-relu’);
relulayer3 = reluLayer(‘Name’, ‘AttentionGate-Stage-3-relu’);
sigmoidlayer1 = sigmoidLayer(‘Name’,’AttentionGate-Stage-1-sigmoid’);
sigmoidlayer2 = sigmoidLayer(‘Name’,’AttentionGate-Stage-2-sigmoid’);
sigmoidlayer3 = sigmoidLayer(‘Name’,’AttentionGate-Stage-3-sigmoid’);
convolution3dlayer11 = convolution3dLayer(1, 512, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-1′);
convolution3dlayer12 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-2′);
convolution3dlayer13 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-3′);
convolution3dlayer21 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-1′);
convolution3dlayer22 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-2′);
convolution3dlayer23 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-3′);
convolution3dlayer31 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-1′);
convolution3dlayer32 = convolution3dLayer(1, 64, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-2′);
convolution3dlayer33 = convolution3dLayer(1, 64, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-3′);
net = addLayers(net, relulayer1);
net = addLayers(net, relulayer2);
net = addLayers(net, relulayer3);
net = addLayers(net, sigmoidlayer1);
net = addLayers(net, sigmoidlayer2);
net = addLayers(net, sigmoidlayer3);
net = addLayers(net, convolution3dlayer11);
net = addLayers(net, convolution3dlayer12);
net = addLayers(net, convolution3dlayer13);
net = addLayers(net, convolution3dlayer21);
net = addLayers(net, convolution3dlayer22);
net = addLayers(net, convolution3dlayer23);
net = addLayers(net, convolution3dlayer31);
net = addLayers(net, convolution3dlayer32);
net = addLayers(net, convolution3dlayer33);
net = disconnectLayers(net, ‘Decoder-Stage-1-UpReLU’, ‘encoderDecoderSkipConnectionCrop3/ref’);
net = disconnectLayers(net, ‘Decoder-Stage-2-UpReLU’, ‘encoderDecoderSkipConnectionCrop2/ref’);
net = disconnectLayers(net, ‘Decoder-Stage-3-UpReLU’, ‘encoderDecoderSkipConnectionCrop1/ref’);
net = disconnectLayers(net, ‘Encoder-Stage-3-DropOut’, ‘encoderDecoderSkipConnectionCrop3/in’);
net = disconnectLayers(net, ‘Encoder-Stage-2-ReLU-2’, ‘encoderDecoderSkipConnectionCrop2/in’);
net = disconnectLayers(net, ‘Encoder-Stage-1-ReLU-2’, ‘encoderDecoderSkipConnectionCrop1/in’);
net = connectLayers(net, ‘Decoder-Stage-1-UpReLU’, ‘AttentionGate-Stage-1-conv-1’);
net = connectLayers(net, ‘Decoder-Stage-2-UpReLU’, ‘AttentionGate-Stage-2-conv-1’);
net = connectLayers(net, ‘Decoder-Stage-3-UpReLU’, ‘AttentionGate-Stage-3-conv-1’);
net = connectLayers(net, ‘Encoder-Stage-3-DropOut’, ‘AttentionGate-Stage-1-conv-2’);
net = connectLayers(net, ‘Encoder-Stage-2-ReLU-2’, ‘AttentionGate-Stage-2-conv-2’);
net = connectLayers(net, ‘Encoder-Stage-1-ReLU-2’, ‘AttentionGate-Stage-3-conv-2’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-1’, ‘encoderDecoderSkipConnectionCrop3/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-1’, ‘encoderDecoderSkipConnectionCrop2/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-1’, ‘encoderDecoderSkipConnectionCrop1/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-2’, ‘encoderDecoderSkipConnectionCrop3/in’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-2’, ‘encoderDecoderSkipConnectionCrop2/in’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-2’, ‘encoderDecoderSkipConnectionCrop1/in’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop3’, ‘encoderDecoderSkipConnectionFeatureMerge3/in1’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop2’, ‘encoderDecoderSkipConnectionFeatureMerge2/in1’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop1’, ‘encoderDecoderSkipConnectionFeatureMerge1/in1’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop3’, ‘AttentionGate-Stage-1-relu’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop2’, ‘AttentionGate-Stage-2-relu’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop1’, ‘AttentionGate-Stage-3-relu’);
net = connectLayers(net, ‘AttentionGate-Stage-1-relu’, ‘AttentionGate-Stage-1-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-3-relu’, ‘AttentionGate-Stage-3-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-2-relu’, ‘AttentionGate-Stage-2-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-3’, ‘AttentionGate-Stage-1-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-3’, ‘AttentionGate-Stage-3-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-3’, ‘AttentionGate-Stage-2-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-1-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge3/in1’);
net = connectLayers(net, ‘AttentionGate-Stage-2-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge2/in1’);
net = connectLayers(net, ‘AttentionGate-Stage-3-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge1/in1’);
% 设置训练选项,使用GPU,启用详细输出,以及其他重要训练参数
options = trainingOptions(‘adam’, …
‘InitialLearnRate’, 1e-4, …
‘LearnRateSchedule’, ‘piecewise’, … % 学习率计划
‘LearnRateDropFactor’, 0.5, … % 学习率降低因子
‘LearnRateDropPeriod’, 5, … % 每5个epochs降低学习率
‘L2Regularization’, 1e-4, … % L2正则化,有助于防止过拟合
‘MaxEpochs’, 10, …
‘MiniBatchSize’, 4, …
‘Verbose’, true, …
‘ValidationData’, dsVal, …
‘ValidationFrequency’, 5, …
‘ValidationPatience’, 20, …
‘Plots’, ‘training-progress’, …
‘ExecutionEnvironment’, ‘gpu’, …
‘CheckpointPath’, ‘X:MATLAB codesStatisticsModeling2’);
analyzeNetwork(net);
net = initialize(net);
% 从验证数据集中读取一个样本
[data, info] = read(dsVal);
image = data{1}; % 图像数据
label = data{2}; % 真实标签
image = double(image);
% 进行预测
predictedLabel = predict(net, image);I am trying to add a ViT module to the UNet constructed by the updated unet3d in MATLAB r2024a, and everything is normal during the training process. I have verified the performance of the model after a certain period of time. The analyzeNetwork function shows no errors, and the size of the front and back connections is 65 * 1024 * 1 (SCB). This is the result of serializing the image.
Incorrect use of dlnetwork/predict (line 658)
Execution failed during layer ‘Transformer PositionEmbedding, Encoder Stage-4 Add-1’.
Error Unet3dTrain (line 288)
PredictedLabel=predict (net, image);
Reason:
Incorrect use of matlab. internal. path. cnn MLFusedNetwork/forwardExampleInputs
Arrays are not compatible for addition
Problem seems to occur when add the vector before position embedding and after position embedding.
There are no issues with adding custom print input size layers before and after this layer.
Here is part of the structure of the network.
My native language is not English, and I am using translation software. Please forgive any errors. The following is the code, which includes non English comments.
Code:
clc; clear;
rng(1);
% ========== 数据读取和数据集创建阶段 ==========
% 指定图像和标签文件的位置
imageDir = ‘X:BaiduDownloadbrats2021ProcessedData’;
labelDir = ‘X:BaiduDownloadbrats2021ProcessedData’; % 标签数据存储在同一位置
% 定义类别名和对应的标签ID
categories = ["background", "necrotic_tumor_core", "peritumoral_edema", "enhancing_tumor"]; % 有4类
labelIDs = [0, 1, 2, 4]; % 分别对应上述类别
% 假定输入数据为 128×128 的体积,有一个背景类和一个肿瘤类
inputSize = [128 128 8 2]; % 最后一个维度1表示1种不同的模态
numClasses = 4; % 类别数(背景和肿瘤)
% 创建图像和标签的数据存储
imds = imageDatastore(imageDir, ‘FileExtensions’,’.mat’, ‘ReadFcn’, @customReadData);
pxds = pixelLabelDatastore(labelDir, categories, labelIDs, ‘FileExtensions’,’.mat’, ‘ReadFcn’, @customReadLabels);
% 分割训练集和验证集
numFiles = numel(imds.Files);
idx = randperm(numFiles); % 随机打乱索引
% numFiles = round(0.001 * numFiles); % 选取小数据集测试
numTrain = round(0.9 * numFiles); % 假设80%的数据用于训练
% 使用索引分割数据
trainImds = subset(imds, idx(1:numTrain));
trainPxds = subset(pxds, idx(1:numTrain));
valImds = subset(imds, idx(numTrain+1:end));
valPxds = subset(pxds, idx(numTrain+1:end));
% 组合训练和验证数据
dsTrain = combine(trainImds, trainPxds);
dsVal = combine(valImds, valPxds);
% 补充函数
function labels = customReadLabels(filename)
fileContent = load(filename);
segmentation = fileContent.segmentation(:,:,74:81);
% 假设原始大小为240×240,计算裁剪偏移
cropSize = 200;
startCrop = (size(segmentation,1) – cropSize) / 2 + 1;
endCrop = startCrop + cropSize – 1;
% 四周均匀裁剪为160×160
croppedSegmentation = segmentation(startCrop:endCrop, startCrop:endCrop, :);
% 重置三维数据大小到128×128,使用最近邻插值方法
segmentationResized = imresize3(croppedSegmentation, [128, 128, size(croppedSegmentation, 3)], ‘Method’, ‘nearest’);
% 创建分类数据,确保使用正确的类别名
labels = categorical(segmentationResized, [0, 1, 2, 4], {‘background’, ‘necrotic_tumor_core’, ‘peritumoral_edema’, ‘enhancing_tumor’});
end
function data = customReadData(filename)
fileContent = load(filename);
% 提取特定切片
originalData = squeeze(fileContent.combinedData(:,:,74:81,[1, 3]));
% 同样计算裁剪偏移
cropSize = 200;
startCrop = (size(originalData,1) – cropSize) / 2 + 1;
endCrop = startCrop + cropSize – 1;
% 四周均匀裁剪为160×160
croppedData = originalData(startCrop:endCrop, startCrop:endCrop, :, :);
% 初始化一个新的四维数组,用于存储调整后的数据
resizedData = zeros(128, 128, size(croppedData, 3), size(croppedData, 4));
% 循环处理每一个通道
for i = 1:size(croppedData, 4)
% 调整每个通道的数据大小并进行灰度化
resizedData(:,:,:,i) = imresize3(mat2gray(croppedData(:,:,:,i)), [128, 128, size(croppedData, 3)]);
end
% 输出处理后的数据
data = resizedData;
end
% 创建3D U-Net网络
net = unet3d(inputSize, numClasses, Encoderdepth = 3);
% ========== Unet网络改造阶段 ==========
% 改造ResBlock
% 对Stage-1进行的操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer = convolution3dLayer([1, 1, 1], 64, ‘Name’, ‘Encoder-Stage-1-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-1-BN-Ident-1’);
addLayer = additionLayer(2, ‘Name’, ‘Encoder-Stage-1-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer);
net = addLayers(net, adjustBnLayer);
net = addLayers(net, addLayer);
% 连接新层
net = connectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-1-Conv-Ident-1’, ‘Encoder-Stage-1-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-1-BN-2′, ‘Encoder-Stage-1-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-1-BN-2’, ‘Encoder-Stage-1-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-1-BN-Ident-1’, ‘Encoder-Stage-1-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-1-Add-1’, ‘Encoder-Stage-1-ReLU-2’);
% 对Stage-2进行的操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer2 = convolution3dLayer([1, 1, 1], 128, ‘Name’, ‘Encoder-Stage-2-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer2 = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-2-BN-Ident-1’);
addLayer2 = additionLayer(2, ‘Name’, ‘Encoder-Stage-2-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer2);
net = addLayers(net, adjustBnLayer2);
net = addLayers(net, addLayer2);
% 连接新层
net = connectLayers(net, ‘Encoder-Stage-1-MaxPool’, ‘Encoder-Stage-2-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-2-Conv-Ident-1’, ‘Encoder-Stage-2-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-2-BN-2′, ‘Encoder-Stage-2-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-2-BN-2’, ‘Encoder-Stage-2-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-2-BN-Ident-1’, ‘Encoder-Stage-2-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-2-Add-1’, ‘Encoder-Stage-2-ReLU-2’);
% 对Stage-3进行操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer3 = convolution3dLayer([1, 1, 1], 256, ‘Name’, ‘Encoder-Stage-3-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer3 = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-3-BN-Ident-1’);
addLayer3 = additionLayer(2, ‘Name’, ‘Encoder-Stage-3-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer3);
net = addLayers(net, adjustBnLayer3);
net = addLayers(net, addLayer3);
% 连接新层
net = connectLayers(net, ‘Encoder-Stage-2-MaxPool’, ‘Encoder-Stage-3-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-3-Conv-Ident-1’, ‘Encoder-Stage-3-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-3-BN-2′, ‘Encoder-Stage-3-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-3-BN-2’, ‘Encoder-Stage-3-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-3-BN-Ident-1’, ‘Encoder-Stage-3-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-3-Add-1’, ‘Encoder-Stage-3-ReLU-2’);
% BatchNormalization改造为GroupNormalization
% 获取网络中所有层的名称
layerNames = {net.Layers.Name};
% 循环遍历所有层的名称,寻找匹配“BN”的层
for i = 1:length(layerNames)
if contains(layerNames{i}, ‘BN’)
% 创建新的组归一化层
gnLayer = groupNormalizationLayer(4, ‘Name’, layerNames{i});
% 替换现有的 BN 层
net = replaceLayer(net, layerNames{i}, gnLayer);
end
end
% 添加Vision Transformer Layer
PatchEmbeddingLayer1 = patchEmbeddingLayer([4 4 2], 1024, ‘Name’, ‘Transformer-PatchEmbedding’);
EmbeddingConcatenationLayer1 = embeddingConcatenationLayer(‘Name’, ‘Transformer-EmbeddingConcatenation’);
PositionEmbeddingLayer1 = positionEmbeddingLayer(1024, 1024, ‘Name’, ‘Transformer-PositionEmbedding’);
addLayer4 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-1’);
addLayer5 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-2’);
addLayer6 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-3’);
dropoutLayer1 = dropoutLayer(0.1, ‘Name’, ‘Transformer-DropOut-1’);
dropoutLayer2 = dropoutLayer(0.1, ‘Name’, ‘Transformer-DropOut-2’);
LayerNormalizationLayer1 = layerNormalizationLayer(‘Name’,’Transformer-LN-1′);
LayerNormalizationLayer2 = layerNormalizationLayer(‘Name’,’Transformer-LN-2′);
SelfAttentionLayer = selfAttentionLayer(8, 32, ‘Name’, ‘Transformer-SelfAttention’);
FullyConnectedLayer = fullyConnectedLayer(1024, ‘Name’, ‘Transformer-fc’);
ReshapeLayer = reshapeLayer(‘Transformer-reshape’);
index1dLayer = indexing1dLayer(‘Name’, ‘Transformer-index1d’);
% printShapeLayer1 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer1’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
% printShapeLayer2 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer2’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
% printShapeLayer3 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer3’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
net = addLayers(net, PatchEmbeddingLayer1);
net = addLayers(net, EmbeddingConcatenationLayer1);
net = addLayers(net, PositionEmbeddingLayer1);
net = addLayers(net, addLayer4);
net = addLayers(net, addLayer5);
net = addLayers(net, addLayer6);
net = addLayers(net, dropoutLayer1);
net = addLayers(net, dropoutLayer2);
net = addLayers(net, LayerNormalizationLayer1);
net = addLayers(net, LayerNormalizationLayer2);
net = addLayers(net, SelfAttentionLayer);
net = addLayers(net, FullyConnectedLayer);
net = addLayers(net, ReshapeLayer);
net = addLayers(net, index1dLayer);
% net = addLayers(net, printShapeLayer1);
% net = addLayers(net, printShapeLayer2);
% net = addLayers(net, printShapeLayer3);
% net = disconnectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-Conv-1’);
% net = disconnectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-BN-Ident-1’);
% net = connectLayers(net, ‘encoderImageInputLayer’, ‘printShapeLayer3’);
% net = connectLayers(net, ‘printShapeLayer3’, ‘Encoder-Stage-1-Conv-1’);
% net = connectLayers(net, ‘printShapeLayer3’, ‘Encoder-Stage-1-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-3-DropOut’, ‘Encoder-Stage-3-MaxPool’);
% net = connectLayers(net,’Encoder-Stage-3-ReLU-2′, ‘printShapeLayer1’);
% net = connectLayers(net,’printShapeLayer1′, ‘Transformer-PatchEmbedding’);
net = connectLayers(net,’Encoder-Stage-3-DropOut’, ‘Transformer-PatchEmbedding’);
net = connectLayers(net, ‘Transformer-PatchEmbedding’, ‘Transformer-EmbeddingConcatenation’);
net = connectLayers(net, ‘Transformer-EmbeddingConcatenation’, ‘Transformer-PositionEmbedding’);
net = connectLayers(net, ‘Transformer-PositionEmbedding’, ‘Encoder-Stage-4-Add-1/in1’);
net = connectLayers(net, ‘Transformer-EmbeddingConcatenation’, ‘Encoder-Stage-4-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-1’, ‘Transformer-DropOut-1’);
net = connectLayers(net, ‘Transformer-DropOut-1’, ‘Transformer-LN-1’);
net = connectLayers(net, ‘Transformer-LN-1’, ‘Transformer-SelfAttention’);
net = connectLayers(net, ‘Transformer-SelfAttention’, ‘Transformer-DropOut-2’);
net = connectLayers(net, ‘Transformer-DropOut-2’, ‘Encoder-Stage-4-Add-2/in1’);
net = connectLayers(net, ‘Transformer-DropOut-1’, ‘Encoder-Stage-4-Add-2/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-2’, ‘Transformer-LN-2’);
net = connectLayers(net, ‘Transformer-LN-2’, ‘Transformer-index1d’);
net = connectLayers(net, ‘Transformer-index1d’, ‘Transformer-fc’);
net = connectLayers(net, ‘Transformer-fc’, ‘Encoder-Stage-4-Add-3/in1’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-2’, ‘Encoder-Stage-4-Add-3/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-3’, ‘Transformer-reshape’);
% net = connectLayers(net, ‘Transformer-reshape’, ‘Encoder-Stage-3-DropOut’);
net = connectLayers(net, ‘Transformer-reshape’, ‘Encoder-Stage-3-MaxPool’);
% net = connectLayers(net, ‘Transformer-reshape’, ‘encoderDecoderSkipConnectionCrop3/in’);
% net = disconnectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘LatentNetwork-Bridge-Conv-1’);
% net = connectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘printShapeLayer2’);
net = removeLayers(net, ‘Encoder-Stage-3-MaxPool’);
net = connectLayers(net, ‘Transformer-reshape’, ‘LatentNetwork-Bridge-Conv-1’);
% net = connectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘LatentNetwork-Bridge-Conv-1’);
% 添加Attention Gate
relulayer1 = reluLayer(‘Name’, ‘AttentionGate-Stage-1-relu’);
relulayer2 = reluLayer(‘Name’, ‘AttentionGate-Stage-2-relu’);
relulayer3 = reluLayer(‘Name’, ‘AttentionGate-Stage-3-relu’);
sigmoidlayer1 = sigmoidLayer(‘Name’,’AttentionGate-Stage-1-sigmoid’);
sigmoidlayer2 = sigmoidLayer(‘Name’,’AttentionGate-Stage-2-sigmoid’);
sigmoidlayer3 = sigmoidLayer(‘Name’,’AttentionGate-Stage-3-sigmoid’);
convolution3dlayer11 = convolution3dLayer(1, 512, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-1′);
convolution3dlayer12 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-2′);
convolution3dlayer13 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-3′);
convolution3dlayer21 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-1′);
convolution3dlayer22 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-2′);
convolution3dlayer23 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-3′);
convolution3dlayer31 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-1′);
convolution3dlayer32 = convolution3dLayer(1, 64, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-2′);
convolution3dlayer33 = convolution3dLayer(1, 64, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-3′);
net = addLayers(net, relulayer1);
net = addLayers(net, relulayer2);
net = addLayers(net, relulayer3);
net = addLayers(net, sigmoidlayer1);
net = addLayers(net, sigmoidlayer2);
net = addLayers(net, sigmoidlayer3);
net = addLayers(net, convolution3dlayer11);
net = addLayers(net, convolution3dlayer12);
net = addLayers(net, convolution3dlayer13);
net = addLayers(net, convolution3dlayer21);
net = addLayers(net, convolution3dlayer22);
net = addLayers(net, convolution3dlayer23);
net = addLayers(net, convolution3dlayer31);
net = addLayers(net, convolution3dlayer32);
net = addLayers(net, convolution3dlayer33);
net = disconnectLayers(net, ‘Decoder-Stage-1-UpReLU’, ‘encoderDecoderSkipConnectionCrop3/ref’);
net = disconnectLayers(net, ‘Decoder-Stage-2-UpReLU’, ‘encoderDecoderSkipConnectionCrop2/ref’);
net = disconnectLayers(net, ‘Decoder-Stage-3-UpReLU’, ‘encoderDecoderSkipConnectionCrop1/ref’);
net = disconnectLayers(net, ‘Encoder-Stage-3-DropOut’, ‘encoderDecoderSkipConnectionCrop3/in’);
net = disconnectLayers(net, ‘Encoder-Stage-2-ReLU-2’, ‘encoderDecoderSkipConnectionCrop2/in’);
net = disconnectLayers(net, ‘Encoder-Stage-1-ReLU-2’, ‘encoderDecoderSkipConnectionCrop1/in’);
net = connectLayers(net, ‘Decoder-Stage-1-UpReLU’, ‘AttentionGate-Stage-1-conv-1’);
net = connectLayers(net, ‘Decoder-Stage-2-UpReLU’, ‘AttentionGate-Stage-2-conv-1’);
net = connectLayers(net, ‘Decoder-Stage-3-UpReLU’, ‘AttentionGate-Stage-3-conv-1’);
net = connectLayers(net, ‘Encoder-Stage-3-DropOut’, ‘AttentionGate-Stage-1-conv-2’);
net = connectLayers(net, ‘Encoder-Stage-2-ReLU-2’, ‘AttentionGate-Stage-2-conv-2’);
net = connectLayers(net, ‘Encoder-Stage-1-ReLU-2’, ‘AttentionGate-Stage-3-conv-2’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-1’, ‘encoderDecoderSkipConnectionCrop3/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-1’, ‘encoderDecoderSkipConnectionCrop2/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-1’, ‘encoderDecoderSkipConnectionCrop1/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-2’, ‘encoderDecoderSkipConnectionCrop3/in’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-2’, ‘encoderDecoderSkipConnectionCrop2/in’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-2’, ‘encoderDecoderSkipConnectionCrop1/in’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop3’, ‘encoderDecoderSkipConnectionFeatureMerge3/in1’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop2’, ‘encoderDecoderSkipConnectionFeatureMerge2/in1’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop1’, ‘encoderDecoderSkipConnectionFeatureMerge1/in1’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop3’, ‘AttentionGate-Stage-1-relu’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop2’, ‘AttentionGate-Stage-2-relu’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop1’, ‘AttentionGate-Stage-3-relu’);
net = connectLayers(net, ‘AttentionGate-Stage-1-relu’, ‘AttentionGate-Stage-1-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-3-relu’, ‘AttentionGate-Stage-3-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-2-relu’, ‘AttentionGate-Stage-2-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-3’, ‘AttentionGate-Stage-1-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-3’, ‘AttentionGate-Stage-3-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-3’, ‘AttentionGate-Stage-2-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-1-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge3/in1’);
net = connectLayers(net, ‘AttentionGate-Stage-2-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge2/in1’);
net = connectLayers(net, ‘AttentionGate-Stage-3-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge1/in1’);
% 设置训练选项,使用GPU,启用详细输出,以及其他重要训练参数
options = trainingOptions(‘adam’, …
‘InitialLearnRate’, 1e-4, …
‘LearnRateSchedule’, ‘piecewise’, … % 学习率计划
‘LearnRateDropFactor’, 0.5, … % 学习率降低因子
‘LearnRateDropPeriod’, 5, … % 每5个epochs降低学习率
‘L2Regularization’, 1e-4, … % L2正则化,有助于防止过拟合
‘MaxEpochs’, 10, …
‘MiniBatchSize’, 4, …
‘Verbose’, true, …
‘ValidationData’, dsVal, …
‘ValidationFrequency’, 5, …
‘ValidationPatience’, 20, …
‘Plots’, ‘training-progress’, …
‘ExecutionEnvironment’, ‘gpu’, …
‘CheckpointPath’, ‘X:MATLAB codesStatisticsModeling2’);
analyzeNetwork(net);
net = initialize(net);
% 从验证数据集中读取一个样本
[data, info] = read(dsVal);
image = data{1}; % 图像数据
label = data{2}; % 真实标签
image = double(image);
% 进行预测
predictedLabel = predict(net, image); I am trying to add a ViT module to the UNet constructed by the updated unet3d in MATLAB r2024a, and everything is normal during the training process. I have verified the performance of the model after a certain period of time. The analyzeNetwork function shows no errors, and the size of the front and back connections is 65 * 1024 * 1 (SCB). This is the result of serializing the image.
Incorrect use of dlnetwork/predict (line 658)
Execution failed during layer ‘Transformer PositionEmbedding, Encoder Stage-4 Add-1’.
Error Unet3dTrain (line 288)
PredictedLabel=predict (net, image);
Reason:
Incorrect use of matlab. internal. path. cnn MLFusedNetwork/forwardExampleInputs
Arrays are not compatible for addition
Problem seems to occur when add the vector before position embedding and after position embedding.
There are no issues with adding custom print input size layers before and after this layer.
Here is part of the structure of the network.
My native language is not English, and I am using translation software. Please forgive any errors. The following is the code, which includes non English comments.
Code:
clc; clear;
rng(1);
% ========== 数据读取和数据集创建阶段 ==========
% 指定图像和标签文件的位置
imageDir = ‘X:BaiduDownloadbrats2021ProcessedData’;
labelDir = ‘X:BaiduDownloadbrats2021ProcessedData’; % 标签数据存储在同一位置
% 定义类别名和对应的标签ID
categories = ["background", "necrotic_tumor_core", "peritumoral_edema", "enhancing_tumor"]; % 有4类
labelIDs = [0, 1, 2, 4]; % 分别对应上述类别
% 假定输入数据为 128×128 的体积,有一个背景类和一个肿瘤类
inputSize = [128 128 8 2]; % 最后一个维度1表示1种不同的模态
numClasses = 4; % 类别数(背景和肿瘤)
% 创建图像和标签的数据存储
imds = imageDatastore(imageDir, ‘FileExtensions’,’.mat’, ‘ReadFcn’, @customReadData);
pxds = pixelLabelDatastore(labelDir, categories, labelIDs, ‘FileExtensions’,’.mat’, ‘ReadFcn’, @customReadLabels);
% 分割训练集和验证集
numFiles = numel(imds.Files);
idx = randperm(numFiles); % 随机打乱索引
% numFiles = round(0.001 * numFiles); % 选取小数据集测试
numTrain = round(0.9 * numFiles); % 假设80%的数据用于训练
% 使用索引分割数据
trainImds = subset(imds, idx(1:numTrain));
trainPxds = subset(pxds, idx(1:numTrain));
valImds = subset(imds, idx(numTrain+1:end));
valPxds = subset(pxds, idx(numTrain+1:end));
% 组合训练和验证数据
dsTrain = combine(trainImds, trainPxds);
dsVal = combine(valImds, valPxds);
% 补充函数
function labels = customReadLabels(filename)
fileContent = load(filename);
segmentation = fileContent.segmentation(:,:,74:81);
% 假设原始大小为240×240,计算裁剪偏移
cropSize = 200;
startCrop = (size(segmentation,1) – cropSize) / 2 + 1;
endCrop = startCrop + cropSize – 1;
% 四周均匀裁剪为160×160
croppedSegmentation = segmentation(startCrop:endCrop, startCrop:endCrop, :);
% 重置三维数据大小到128×128,使用最近邻插值方法
segmentationResized = imresize3(croppedSegmentation, [128, 128, size(croppedSegmentation, 3)], ‘Method’, ‘nearest’);
% 创建分类数据,确保使用正确的类别名
labels = categorical(segmentationResized, [0, 1, 2, 4], {‘background’, ‘necrotic_tumor_core’, ‘peritumoral_edema’, ‘enhancing_tumor’});
end
function data = customReadData(filename)
fileContent = load(filename);
% 提取特定切片
originalData = squeeze(fileContent.combinedData(:,:,74:81,[1, 3]));
% 同样计算裁剪偏移
cropSize = 200;
startCrop = (size(originalData,1) – cropSize) / 2 + 1;
endCrop = startCrop + cropSize – 1;
% 四周均匀裁剪为160×160
croppedData = originalData(startCrop:endCrop, startCrop:endCrop, :, :);
% 初始化一个新的四维数组,用于存储调整后的数据
resizedData = zeros(128, 128, size(croppedData, 3), size(croppedData, 4));
% 循环处理每一个通道
for i = 1:size(croppedData, 4)
% 调整每个通道的数据大小并进行灰度化
resizedData(:,:,:,i) = imresize3(mat2gray(croppedData(:,:,:,i)), [128, 128, size(croppedData, 3)]);
end
% 输出处理后的数据
data = resizedData;
end
% 创建3D U-Net网络
net = unet3d(inputSize, numClasses, Encoderdepth = 3);
% ========== Unet网络改造阶段 ==========
% 改造ResBlock
% 对Stage-1进行的操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer = convolution3dLayer([1, 1, 1], 64, ‘Name’, ‘Encoder-Stage-1-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-1-BN-Ident-1’);
addLayer = additionLayer(2, ‘Name’, ‘Encoder-Stage-1-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer);
net = addLayers(net, adjustBnLayer);
net = addLayers(net, addLayer);
% 连接新层
net = connectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-1-Conv-Ident-1’, ‘Encoder-Stage-1-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-1-BN-2′, ‘Encoder-Stage-1-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-1-BN-2’, ‘Encoder-Stage-1-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-1-BN-Ident-1’, ‘Encoder-Stage-1-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-1-Add-1’, ‘Encoder-Stage-1-ReLU-2’);
% 对Stage-2进行的操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer2 = convolution3dLayer([1, 1, 1], 128, ‘Name’, ‘Encoder-Stage-2-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer2 = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-2-BN-Ident-1’);
addLayer2 = additionLayer(2, ‘Name’, ‘Encoder-Stage-2-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer2);
net = addLayers(net, adjustBnLayer2);
net = addLayers(net, addLayer2);
% 连接新层
net = connectLayers(net, ‘Encoder-Stage-1-MaxPool’, ‘Encoder-Stage-2-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-2-Conv-Ident-1’, ‘Encoder-Stage-2-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-2-BN-2′, ‘Encoder-Stage-2-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-2-BN-2’, ‘Encoder-Stage-2-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-2-BN-Ident-1’, ‘Encoder-Stage-2-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-2-Add-1’, ‘Encoder-Stage-2-ReLU-2’);
% 对Stage-3进行操作
% 添加一个1x1x1卷积层以适应通道数
adjustConvLayer3 = convolution3dLayer([1, 1, 1], 256, ‘Name’, ‘Encoder-Stage-3-Conv-Ident-1’, ‘Padding’, ‘same’);
adjustBnLayer3 = batchNormalizationLayer(‘Name’, ‘Encoder-Stage-3-BN-Ident-1’);
addLayer3 = additionLayer(2, ‘Name’, ‘Encoder-Stage-3-Add-1’);
% 添加层到图
net = addLayers(net, adjustConvLayer3);
net = addLayers(net, adjustBnLayer3);
net = addLayers(net, addLayer3);
% 连接新层
net = connectLayers(net, ‘Encoder-Stage-2-MaxPool’, ‘Encoder-Stage-3-Conv-Ident-1’);
net = connectLayers(net, ‘Encoder-Stage-3-Conv-Ident-1’, ‘Encoder-Stage-3-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-3-BN-2′, ‘Encoder-Stage-3-ReLU-2’);
net = connectLayers(net, ‘Encoder-Stage-3-BN-2’, ‘Encoder-Stage-3-Add-1/in1’);
net = connectLayers(net, ‘Encoder-Stage-3-BN-Ident-1’, ‘Encoder-Stage-3-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-3-Add-1’, ‘Encoder-Stage-3-ReLU-2’);
% BatchNormalization改造为GroupNormalization
% 获取网络中所有层的名称
layerNames = {net.Layers.Name};
% 循环遍历所有层的名称,寻找匹配“BN”的层
for i = 1:length(layerNames)
if contains(layerNames{i}, ‘BN’)
% 创建新的组归一化层
gnLayer = groupNormalizationLayer(4, ‘Name’, layerNames{i});
% 替换现有的 BN 层
net = replaceLayer(net, layerNames{i}, gnLayer);
end
end
% 添加Vision Transformer Layer
PatchEmbeddingLayer1 = patchEmbeddingLayer([4 4 2], 1024, ‘Name’, ‘Transformer-PatchEmbedding’);
EmbeddingConcatenationLayer1 = embeddingConcatenationLayer(‘Name’, ‘Transformer-EmbeddingConcatenation’);
PositionEmbeddingLayer1 = positionEmbeddingLayer(1024, 1024, ‘Name’, ‘Transformer-PositionEmbedding’);
addLayer4 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-1’);
addLayer5 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-2’);
addLayer6 = additionLayer(2, ‘Name’, ‘Encoder-Stage-4-Add-3’);
dropoutLayer1 = dropoutLayer(0.1, ‘Name’, ‘Transformer-DropOut-1’);
dropoutLayer2 = dropoutLayer(0.1, ‘Name’, ‘Transformer-DropOut-2’);
LayerNormalizationLayer1 = layerNormalizationLayer(‘Name’,’Transformer-LN-1′);
LayerNormalizationLayer2 = layerNormalizationLayer(‘Name’,’Transformer-LN-2′);
SelfAttentionLayer = selfAttentionLayer(8, 32, ‘Name’, ‘Transformer-SelfAttention’);
FullyConnectedLayer = fullyConnectedLayer(1024, ‘Name’, ‘Transformer-fc’);
ReshapeLayer = reshapeLayer(‘Transformer-reshape’);
index1dLayer = indexing1dLayer(‘Name’, ‘Transformer-index1d’);
% printShapeLayer1 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer1’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
% printShapeLayer2 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer2’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
% printShapeLayer3 = functionLayer(@printShape, …
% ‘Name’, ‘printShapeLayer3’, …
% ‘NumInputs’, 1, …
% ‘NumOutputs’, 1, …
% ‘InputNames’, {‘in’}, …
% ‘OutputNames’, {‘out’});
net = addLayers(net, PatchEmbeddingLayer1);
net = addLayers(net, EmbeddingConcatenationLayer1);
net = addLayers(net, PositionEmbeddingLayer1);
net = addLayers(net, addLayer4);
net = addLayers(net, addLayer5);
net = addLayers(net, addLayer6);
net = addLayers(net, dropoutLayer1);
net = addLayers(net, dropoutLayer2);
net = addLayers(net, LayerNormalizationLayer1);
net = addLayers(net, LayerNormalizationLayer2);
net = addLayers(net, SelfAttentionLayer);
net = addLayers(net, FullyConnectedLayer);
net = addLayers(net, ReshapeLayer);
net = addLayers(net, index1dLayer);
% net = addLayers(net, printShapeLayer1);
% net = addLayers(net, printShapeLayer2);
% net = addLayers(net, printShapeLayer3);
% net = disconnectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-Conv-1’);
% net = disconnectLayers(net, ‘encoderImageInputLayer’, ‘Encoder-Stage-1-BN-Ident-1’);
% net = connectLayers(net, ‘encoderImageInputLayer’, ‘printShapeLayer3’);
% net = connectLayers(net, ‘printShapeLayer3’, ‘Encoder-Stage-1-Conv-1’);
% net = connectLayers(net, ‘printShapeLayer3’, ‘Encoder-Stage-1-BN-Ident-1’);
net = disconnectLayers(net,’Encoder-Stage-3-DropOut’, ‘Encoder-Stage-3-MaxPool’);
% net = connectLayers(net,’Encoder-Stage-3-ReLU-2′, ‘printShapeLayer1’);
% net = connectLayers(net,’printShapeLayer1′, ‘Transformer-PatchEmbedding’);
net = connectLayers(net,’Encoder-Stage-3-DropOut’, ‘Transformer-PatchEmbedding’);
net = connectLayers(net, ‘Transformer-PatchEmbedding’, ‘Transformer-EmbeddingConcatenation’);
net = connectLayers(net, ‘Transformer-EmbeddingConcatenation’, ‘Transformer-PositionEmbedding’);
net = connectLayers(net, ‘Transformer-PositionEmbedding’, ‘Encoder-Stage-4-Add-1/in1’);
net = connectLayers(net, ‘Transformer-EmbeddingConcatenation’, ‘Encoder-Stage-4-Add-1/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-1’, ‘Transformer-DropOut-1’);
net = connectLayers(net, ‘Transformer-DropOut-1’, ‘Transformer-LN-1’);
net = connectLayers(net, ‘Transformer-LN-1’, ‘Transformer-SelfAttention’);
net = connectLayers(net, ‘Transformer-SelfAttention’, ‘Transformer-DropOut-2’);
net = connectLayers(net, ‘Transformer-DropOut-2’, ‘Encoder-Stage-4-Add-2/in1’);
net = connectLayers(net, ‘Transformer-DropOut-1’, ‘Encoder-Stage-4-Add-2/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-2’, ‘Transformer-LN-2’);
net = connectLayers(net, ‘Transformer-LN-2’, ‘Transformer-index1d’);
net = connectLayers(net, ‘Transformer-index1d’, ‘Transformer-fc’);
net = connectLayers(net, ‘Transformer-fc’, ‘Encoder-Stage-4-Add-3/in1’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-2’, ‘Encoder-Stage-4-Add-3/in2’);
net = connectLayers(net, ‘Encoder-Stage-4-Add-3’, ‘Transformer-reshape’);
% net = connectLayers(net, ‘Transformer-reshape’, ‘Encoder-Stage-3-DropOut’);
net = connectLayers(net, ‘Transformer-reshape’, ‘Encoder-Stage-3-MaxPool’);
% net = connectLayers(net, ‘Transformer-reshape’, ‘encoderDecoderSkipConnectionCrop3/in’);
% net = disconnectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘LatentNetwork-Bridge-Conv-1’);
% net = connectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘printShapeLayer2’);
net = removeLayers(net, ‘Encoder-Stage-3-MaxPool’);
net = connectLayers(net, ‘Transformer-reshape’, ‘LatentNetwork-Bridge-Conv-1’);
% net = connectLayers(net, ‘Encoder-Stage-3-MaxPool’, ‘LatentNetwork-Bridge-Conv-1’);
% 添加Attention Gate
relulayer1 = reluLayer(‘Name’, ‘AttentionGate-Stage-1-relu’);
relulayer2 = reluLayer(‘Name’, ‘AttentionGate-Stage-2-relu’);
relulayer3 = reluLayer(‘Name’, ‘AttentionGate-Stage-3-relu’);
sigmoidlayer1 = sigmoidLayer(‘Name’,’AttentionGate-Stage-1-sigmoid’);
sigmoidlayer2 = sigmoidLayer(‘Name’,’AttentionGate-Stage-2-sigmoid’);
sigmoidlayer3 = sigmoidLayer(‘Name’,’AttentionGate-Stage-3-sigmoid’);
convolution3dlayer11 = convolution3dLayer(1, 512, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-1′);
convolution3dlayer12 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-2′);
convolution3dlayer13 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-1-conv-3′);
convolution3dlayer21 = convolution3dLayer(1, 256, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-1′);
convolution3dlayer22 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-2′);
convolution3dlayer23 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-2-conv-3′);
convolution3dlayer31 = convolution3dLayer(1, 128, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-1′);
convolution3dlayer32 = convolution3dLayer(1, 64, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-2′);
convolution3dlayer33 = convolution3dLayer(1, 64, ‘Padding’,’same’, ‘Name’,’AttentionGate-Stage-3-conv-3′);
net = addLayers(net, relulayer1);
net = addLayers(net, relulayer2);
net = addLayers(net, relulayer3);
net = addLayers(net, sigmoidlayer1);
net = addLayers(net, sigmoidlayer2);
net = addLayers(net, sigmoidlayer3);
net = addLayers(net, convolution3dlayer11);
net = addLayers(net, convolution3dlayer12);
net = addLayers(net, convolution3dlayer13);
net = addLayers(net, convolution3dlayer21);
net = addLayers(net, convolution3dlayer22);
net = addLayers(net, convolution3dlayer23);
net = addLayers(net, convolution3dlayer31);
net = addLayers(net, convolution3dlayer32);
net = addLayers(net, convolution3dlayer33);
net = disconnectLayers(net, ‘Decoder-Stage-1-UpReLU’, ‘encoderDecoderSkipConnectionCrop3/ref’);
net = disconnectLayers(net, ‘Decoder-Stage-2-UpReLU’, ‘encoderDecoderSkipConnectionCrop2/ref’);
net = disconnectLayers(net, ‘Decoder-Stage-3-UpReLU’, ‘encoderDecoderSkipConnectionCrop1/ref’);
net = disconnectLayers(net, ‘Encoder-Stage-3-DropOut’, ‘encoderDecoderSkipConnectionCrop3/in’);
net = disconnectLayers(net, ‘Encoder-Stage-2-ReLU-2’, ‘encoderDecoderSkipConnectionCrop2/in’);
net = disconnectLayers(net, ‘Encoder-Stage-1-ReLU-2’, ‘encoderDecoderSkipConnectionCrop1/in’);
net = connectLayers(net, ‘Decoder-Stage-1-UpReLU’, ‘AttentionGate-Stage-1-conv-1’);
net = connectLayers(net, ‘Decoder-Stage-2-UpReLU’, ‘AttentionGate-Stage-2-conv-1’);
net = connectLayers(net, ‘Decoder-Stage-3-UpReLU’, ‘AttentionGate-Stage-3-conv-1’);
net = connectLayers(net, ‘Encoder-Stage-3-DropOut’, ‘AttentionGate-Stage-1-conv-2’);
net = connectLayers(net, ‘Encoder-Stage-2-ReLU-2’, ‘AttentionGate-Stage-2-conv-2’);
net = connectLayers(net, ‘Encoder-Stage-1-ReLU-2’, ‘AttentionGate-Stage-3-conv-2’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-1’, ‘encoderDecoderSkipConnectionCrop3/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-1’, ‘encoderDecoderSkipConnectionCrop2/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-1’, ‘encoderDecoderSkipConnectionCrop1/ref’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-2’, ‘encoderDecoderSkipConnectionCrop3/in’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-2’, ‘encoderDecoderSkipConnectionCrop2/in’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-2’, ‘encoderDecoderSkipConnectionCrop1/in’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop3’, ‘encoderDecoderSkipConnectionFeatureMerge3/in1’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop2’, ‘encoderDecoderSkipConnectionFeatureMerge2/in1’);
net = disconnectLayers(net, ‘encoderDecoderSkipConnectionCrop1’, ‘encoderDecoderSkipConnectionFeatureMerge1/in1’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop3’, ‘AttentionGate-Stage-1-relu’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop2’, ‘AttentionGate-Stage-2-relu’);
net = connectLayers(net, ‘encoderDecoderSkipConnectionCrop1’, ‘AttentionGate-Stage-3-relu’);
net = connectLayers(net, ‘AttentionGate-Stage-1-relu’, ‘AttentionGate-Stage-1-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-3-relu’, ‘AttentionGate-Stage-3-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-2-relu’, ‘AttentionGate-Stage-2-conv-3’);
net = connectLayers(net, ‘AttentionGate-Stage-1-conv-3’, ‘AttentionGate-Stage-1-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-3-conv-3’, ‘AttentionGate-Stage-3-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-2-conv-3’, ‘AttentionGate-Stage-2-sigmoid’);
net = connectLayers(net, ‘AttentionGate-Stage-1-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge3/in1’);
net = connectLayers(net, ‘AttentionGate-Stage-2-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge2/in1’);
net = connectLayers(net, ‘AttentionGate-Stage-3-sigmoid’, ‘encoderDecoderSkipConnectionFeatureMerge1/in1’);
% 设置训练选项,使用GPU,启用详细输出,以及其他重要训练参数
options = trainingOptions(‘adam’, …
‘InitialLearnRate’, 1e-4, …
‘LearnRateSchedule’, ‘piecewise’, … % 学习率计划
‘LearnRateDropFactor’, 0.5, … % 学习率降低因子
‘LearnRateDropPeriod’, 5, … % 每5个epochs降低学习率
‘L2Regularization’, 1e-4, … % L2正则化,有助于防止过拟合
‘MaxEpochs’, 10, …
‘MiniBatchSize’, 4, …
‘Verbose’, true, …
‘ValidationData’, dsVal, …
‘ValidationFrequency’, 5, …
‘ValidationPatience’, 20, …
‘Plots’, ‘training-progress’, …
‘ExecutionEnvironment’, ‘gpu’, …
‘CheckpointPath’, ‘X:MATLAB codesStatisticsModeling2’);
analyzeNetwork(net);
net = initialize(net);
% 从验证数据集中读取一个样本
[data, info] = read(dsVal);
image = data{1}; % 图像数据
label = data{2}; % 真实标签
image = double(image);
% 进行预测
predictedLabel = predict(net, image); unet3d, visiontransformer, transunet MATLAB Answers — New Questions
help with nested loop and plot
hello everyone, i need help with the following code.
i am trying to plot the boundary of the region that satisfies the following conditions:
solve and plot for x and y
x+y+e+t>=0
And
x*y-e*t>=0
where x and y are the two variables while e and t are two constants whose values has to vary in a range.
so far i have got (which is working fine for fixed e and t):
n= 101;
x = linspace(-100, 100, n);
y = linspace(-100, 100, n);
[X, Y] = meshgrid(x, y);
Z = zeros(n, n);
e= 10;
t=-25;
B = X + Y + e + t;
D = X.*Y – e.*t;
for i= 1:n
for j= 1:n
if B(i,j) >= 0
Z(i,j) = D(i,j);
else
Z(i,j) = -1;
end
end
end
v = [0,0];
contour(X,Y,Z,v, ‘LineWidth’, 1.5)
grid on
axis equal
xline(0, ‘Color’, ‘k’, ‘LineWidth’, 0.5);
yline(0, ‘Color’, ‘k’, ‘LineWidth’, 0.5);
now i would like to see the effects of the two constants e and t on the above mentioned boundary. i would like to plot different curves with varying e and t on the same graph but i am having troubles to understand an efficient way to do it.
e and t are two arrays such as linspace(-25, 25, 3), so i want to check how the plot evolves over 3×3 combiations of e and t.
i tried nesting for loops but it didn’t work as i got a blank plot. could anybody please give me any suggestions as to do it with for loops or with any other way?
i know i could do it "manually", changing e and t every time and using hold on to plot the curves on the same figure but it is rather inefficient.
thanks to anyone who will helphello everyone, i need help with the following code.
i am trying to plot the boundary of the region that satisfies the following conditions:
solve and plot for x and y
x+y+e+t>=0
And
x*y-e*t>=0
where x and y are the two variables while e and t are two constants whose values has to vary in a range.
so far i have got (which is working fine for fixed e and t):
n= 101;
x = linspace(-100, 100, n);
y = linspace(-100, 100, n);
[X, Y] = meshgrid(x, y);
Z = zeros(n, n);
e= 10;
t=-25;
B = X + Y + e + t;
D = X.*Y – e.*t;
for i= 1:n
for j= 1:n
if B(i,j) >= 0
Z(i,j) = D(i,j);
else
Z(i,j) = -1;
end
end
end
v = [0,0];
contour(X,Y,Z,v, ‘LineWidth’, 1.5)
grid on
axis equal
xline(0, ‘Color’, ‘k’, ‘LineWidth’, 0.5);
yline(0, ‘Color’, ‘k’, ‘LineWidth’, 0.5);
now i would like to see the effects of the two constants e and t on the above mentioned boundary. i would like to plot different curves with varying e and t on the same graph but i am having troubles to understand an efficient way to do it.
e and t are two arrays such as linspace(-25, 25, 3), so i want to check how the plot evolves over 3×3 combiations of e and t.
i tried nesting for loops but it didn’t work as i got a blank plot. could anybody please give me any suggestions as to do it with for loops or with any other way?
i know i could do it "manually", changing e and t every time and using hold on to plot the curves on the same figure but it is rather inefficient.
thanks to anyone who will help hello everyone, i need help with the following code.
i am trying to plot the boundary of the region that satisfies the following conditions:
solve and plot for x and y
x+y+e+t>=0
And
x*y-e*t>=0
where x and y are the two variables while e and t are two constants whose values has to vary in a range.
so far i have got (which is working fine for fixed e and t):
n= 101;
x = linspace(-100, 100, n);
y = linspace(-100, 100, n);
[X, Y] = meshgrid(x, y);
Z = zeros(n, n);
e= 10;
t=-25;
B = X + Y + e + t;
D = X.*Y – e.*t;
for i= 1:n
for j= 1:n
if B(i,j) >= 0
Z(i,j) = D(i,j);
else
Z(i,j) = -1;
end
end
end
v = [0,0];
contour(X,Y,Z,v, ‘LineWidth’, 1.5)
grid on
axis equal
xline(0, ‘Color’, ‘k’, ‘LineWidth’, 0.5);
yline(0, ‘Color’, ‘k’, ‘LineWidth’, 0.5);
now i would like to see the effects of the two constants e and t on the above mentioned boundary. i would like to plot different curves with varying e and t on the same graph but i am having troubles to understand an efficient way to do it.
e and t are two arrays such as linspace(-25, 25, 3), so i want to check how the plot evolves over 3×3 combiations of e and t.
i tried nesting for loops but it didn’t work as i got a blank plot. could anybody please give me any suggestions as to do it with for loops or with any other way?
i know i could do it "manually", changing e and t every time and using hold on to plot the curves on the same figure but it is rather inefficient.
thanks to anyone who will help nested loops, for loop, plot, hold, loops, cycles, grid, meshgrid MATLAB Answers — New Questions
Can we change the Constraints in MPC ?
Hello,
I’m using the Online feature of mpc block .i.e varying the MV constraints with simulation time.
Is it posible to change the inequality of the constraints in mpc block in matlab/simulink?
For example:
If ECR values (V) is 0 and scale factor is 1, then
default constraint is : u_min <= u <= u_max
and I would like to change to : u_min < u < u_maxHello,
I’m using the Online feature of mpc block .i.e varying the MV constraints with simulation time.
Is it posible to change the inequality of the constraints in mpc block in matlab/simulink?
For example:
If ECR values (V) is 0 and scale factor is 1, then
default constraint is : u_min <= u <= u_max
and I would like to change to : u_min < u < u_max Hello,
I’m using the Online feature of mpc block .i.e varying the MV constraints with simulation time.
Is it posible to change the inequality of the constraints in mpc block in matlab/simulink?
For example:
If ECR values (V) is 0 and scale factor is 1, then
default constraint is : u_min <= u <= u_max
and I would like to change to : u_min < u < u_max constraints, simulink, model predictive control, mpc MATLAB Answers — New Questions