Category: Matlab
Category Archives: Matlab
How do I plot the receivedFlag from Simulink?
https://kr.mathworks.com/help/driving/ug/truck-platooning-with-roadrunner-scenario.html
classdef HelperV2VReceiver < matlab.System
% HelperV2VReceiver Models a V2V receiver.
% The V2V Receiver receives the Basic Safety Message transmitted by the
% target vehicles based on SNR graphs. The SNR data is adjusted based
% on the range and loaded during simulation.
% NOTE: The name of this System Object and its functionality may
% change without notice in a future release,
% or the System Object itself may be removed.
% Copyright 2021-2023 The MathWorks, Inc.
properties(Nontunable)
% V2V Channel Info
SnrCurves = struct;
% Output Struct
OutputStruct = struct;
end
% Pre-computed constants
properties(Access = private)
% Holds the information of precomputed snr curves
DistanceToSnrInfo
SnrToTputInfo
% Holds the information of snr & distance limits
MaxVehDist;
SnrMin;
SnrMax;
% Maximum range
MaxRange = 1000;
% Output Bus
BSMOut
% Minimum Throughput Percentage
MinTput = 60;
end
methods(Access = protected)
function sts = getSampleTimeImpl(obj)
sts = createSampleTime(obj,’Type’,’Inherited’);
end
function setupImpl(obj)
% Distance to SNR Relation
obj.DistanceToSnrInfo = obj.SnrCurves.dist2snr;
% SNR to Throughput Relation
obj.SnrToTputInfo = obj.SnrCurves.snr2tput;
% Get the limits for Distance & SNR
obj.MaxVehDist = obj.DistanceToSnrInfo(end,1);
obj.SnrMin = obj.SnrToTputInfo(1,1);
obj.SnrMax = obj.SnrToTputInfo(end,1);
% Initialize Output Bus
obj.BSMOut = obj.OutputStruct;
end
function bsmOut = stepImpl(obj,bsm,egoPose,sceneOrigin)
numReceivedSignal = 0;
bsmOut = obj.BSMOut;
bsmOutIdx = 1;
for i = 1:bsm.NumOfBSM
if bsm.BSMCoreData(i).Id > 0
% Compute the Ego to Target Vehicle distance
vehPos = [0,0,0];
lla = [double(bsm.BSMCoreData(i).Lattitude)*10^-7,double(bsm.BSMCoreData(i).Longitude)*10^-7,double(bsm.BSMCoreData(i).Elevation)*0.1];
% Convert geographic coordinates to local Cartesian coordinates
[vehPos(1),vehPos(2),vehPos(3)] = latlon2local(lla(1),lla(2),lla(3),sceneOrigin);
v2vdist = norm(egoPose.Position – vehPos);
% Find the throughput percentage for the v2vdist using
% the precomputed snr curves.
if v2vdist<obj.MaxVehDist
v2vdist = max(1,round(v2vdist));
snrEstimate = min(max(obj.SnrMin,interp1(obj.DistanceToSnrInfo(:,1),obj.DistanceToSnrInfo(:,2),v2vdist)),obj.SnrMax);
tput = interp1(obj.SnrToTputInfo(:,1),obj.SnrToTputInfo(:,2),snrEstimate);
else
tput = 0;
end
% Receive the signal based on throughput
receivedFlag = randi([obj.MinTput 100]) <= tput;
if receivedFlag
numReceivedSignal = numReceivedSignal+1;
bsmOut.IsValidTime = true;
bsmOut.BSMCoreData(bsmOutIdx) = bsm.BSMCoreData(i);
bsmOutIdx = bsmOutIdx+1;
end
end
end
bsmOut.NumOfBSM = numReceivedSignal;
end
function bsmOut = getOutputSizeImpl(obj) %#ok<MANU>
% Return size for each output port
bsmOut = 1;
end
function bsmOut = getOutputDataTypeImpl(obj) %#ok<MANU>
% Return data type for each output port
bsmOut = ‘BusBSM’;
end
function bsmOut = isOutputComplexImpl(obj) %#ok<MANU>
% Return true for each output port with complex data
bsmOut = false;
end
function bsmOut = isOutputFixedSizeImpl(obj) %#ok<MANU>
% Return true for each output port with fixed size
bsmOut = true;
end
end
methods(Access = protected, Static)
function flag = showSimulateUsingImpl
% Return false if simulation mode hidden in System block dialog
flag = true;
end
end
end
I would like to obtain the receivedFlag value from the HelperV2VReceiver code in the Follower1 Simulink example and plot it in platooning.mlx. What should I do?https://kr.mathworks.com/help/driving/ug/truck-platooning-with-roadrunner-scenario.html
classdef HelperV2VReceiver < matlab.System
% HelperV2VReceiver Models a V2V receiver.
% The V2V Receiver receives the Basic Safety Message transmitted by the
% target vehicles based on SNR graphs. The SNR data is adjusted based
% on the range and loaded during simulation.
% NOTE: The name of this System Object and its functionality may
% change without notice in a future release,
% or the System Object itself may be removed.
% Copyright 2021-2023 The MathWorks, Inc.
properties(Nontunable)
% V2V Channel Info
SnrCurves = struct;
% Output Struct
OutputStruct = struct;
end
% Pre-computed constants
properties(Access = private)
% Holds the information of precomputed snr curves
DistanceToSnrInfo
SnrToTputInfo
% Holds the information of snr & distance limits
MaxVehDist;
SnrMin;
SnrMax;
% Maximum range
MaxRange = 1000;
% Output Bus
BSMOut
% Minimum Throughput Percentage
MinTput = 60;
end
methods(Access = protected)
function sts = getSampleTimeImpl(obj)
sts = createSampleTime(obj,’Type’,’Inherited’);
end
function setupImpl(obj)
% Distance to SNR Relation
obj.DistanceToSnrInfo = obj.SnrCurves.dist2snr;
% SNR to Throughput Relation
obj.SnrToTputInfo = obj.SnrCurves.snr2tput;
% Get the limits for Distance & SNR
obj.MaxVehDist = obj.DistanceToSnrInfo(end,1);
obj.SnrMin = obj.SnrToTputInfo(1,1);
obj.SnrMax = obj.SnrToTputInfo(end,1);
% Initialize Output Bus
obj.BSMOut = obj.OutputStruct;
end
function bsmOut = stepImpl(obj,bsm,egoPose,sceneOrigin)
numReceivedSignal = 0;
bsmOut = obj.BSMOut;
bsmOutIdx = 1;
for i = 1:bsm.NumOfBSM
if bsm.BSMCoreData(i).Id > 0
% Compute the Ego to Target Vehicle distance
vehPos = [0,0,0];
lla = [double(bsm.BSMCoreData(i).Lattitude)*10^-7,double(bsm.BSMCoreData(i).Longitude)*10^-7,double(bsm.BSMCoreData(i).Elevation)*0.1];
% Convert geographic coordinates to local Cartesian coordinates
[vehPos(1),vehPos(2),vehPos(3)] = latlon2local(lla(1),lla(2),lla(3),sceneOrigin);
v2vdist = norm(egoPose.Position – vehPos);
% Find the throughput percentage for the v2vdist using
% the precomputed snr curves.
if v2vdist<obj.MaxVehDist
v2vdist = max(1,round(v2vdist));
snrEstimate = min(max(obj.SnrMin,interp1(obj.DistanceToSnrInfo(:,1),obj.DistanceToSnrInfo(:,2),v2vdist)),obj.SnrMax);
tput = interp1(obj.SnrToTputInfo(:,1),obj.SnrToTputInfo(:,2),snrEstimate);
else
tput = 0;
end
% Receive the signal based on throughput
receivedFlag = randi([obj.MinTput 100]) <= tput;
if receivedFlag
numReceivedSignal = numReceivedSignal+1;
bsmOut.IsValidTime = true;
bsmOut.BSMCoreData(bsmOutIdx) = bsm.BSMCoreData(i);
bsmOutIdx = bsmOutIdx+1;
end
end
end
bsmOut.NumOfBSM = numReceivedSignal;
end
function bsmOut = getOutputSizeImpl(obj) %#ok<MANU>
% Return size for each output port
bsmOut = 1;
end
function bsmOut = getOutputDataTypeImpl(obj) %#ok<MANU>
% Return data type for each output port
bsmOut = ‘BusBSM’;
end
function bsmOut = isOutputComplexImpl(obj) %#ok<MANU>
% Return true for each output port with complex data
bsmOut = false;
end
function bsmOut = isOutputFixedSizeImpl(obj) %#ok<MANU>
% Return true for each output port with fixed size
bsmOut = true;
end
end
methods(Access = protected, Static)
function flag = showSimulateUsingImpl
% Return false if simulation mode hidden in System block dialog
flag = true;
end
end
end
I would like to obtain the receivedFlag value from the HelperV2VReceiver code in the Follower1 Simulink example and plot it in platooning.mlx. What should I do? https://kr.mathworks.com/help/driving/ug/truck-platooning-with-roadrunner-scenario.html
classdef HelperV2VReceiver < matlab.System
% HelperV2VReceiver Models a V2V receiver.
% The V2V Receiver receives the Basic Safety Message transmitted by the
% target vehicles based on SNR graphs. The SNR data is adjusted based
% on the range and loaded during simulation.
% NOTE: The name of this System Object and its functionality may
% change without notice in a future release,
% or the System Object itself may be removed.
% Copyright 2021-2023 The MathWorks, Inc.
properties(Nontunable)
% V2V Channel Info
SnrCurves = struct;
% Output Struct
OutputStruct = struct;
end
% Pre-computed constants
properties(Access = private)
% Holds the information of precomputed snr curves
DistanceToSnrInfo
SnrToTputInfo
% Holds the information of snr & distance limits
MaxVehDist;
SnrMin;
SnrMax;
% Maximum range
MaxRange = 1000;
% Output Bus
BSMOut
% Minimum Throughput Percentage
MinTput = 60;
end
methods(Access = protected)
function sts = getSampleTimeImpl(obj)
sts = createSampleTime(obj,’Type’,’Inherited’);
end
function setupImpl(obj)
% Distance to SNR Relation
obj.DistanceToSnrInfo = obj.SnrCurves.dist2snr;
% SNR to Throughput Relation
obj.SnrToTputInfo = obj.SnrCurves.snr2tput;
% Get the limits for Distance & SNR
obj.MaxVehDist = obj.DistanceToSnrInfo(end,1);
obj.SnrMin = obj.SnrToTputInfo(1,1);
obj.SnrMax = obj.SnrToTputInfo(end,1);
% Initialize Output Bus
obj.BSMOut = obj.OutputStruct;
end
function bsmOut = stepImpl(obj,bsm,egoPose,sceneOrigin)
numReceivedSignal = 0;
bsmOut = obj.BSMOut;
bsmOutIdx = 1;
for i = 1:bsm.NumOfBSM
if bsm.BSMCoreData(i).Id > 0
% Compute the Ego to Target Vehicle distance
vehPos = [0,0,0];
lla = [double(bsm.BSMCoreData(i).Lattitude)*10^-7,double(bsm.BSMCoreData(i).Longitude)*10^-7,double(bsm.BSMCoreData(i).Elevation)*0.1];
% Convert geographic coordinates to local Cartesian coordinates
[vehPos(1),vehPos(2),vehPos(3)] = latlon2local(lla(1),lla(2),lla(3),sceneOrigin);
v2vdist = norm(egoPose.Position – vehPos);
% Find the throughput percentage for the v2vdist using
% the precomputed snr curves.
if v2vdist<obj.MaxVehDist
v2vdist = max(1,round(v2vdist));
snrEstimate = min(max(obj.SnrMin,interp1(obj.DistanceToSnrInfo(:,1),obj.DistanceToSnrInfo(:,2),v2vdist)),obj.SnrMax);
tput = interp1(obj.SnrToTputInfo(:,1),obj.SnrToTputInfo(:,2),snrEstimate);
else
tput = 0;
end
% Receive the signal based on throughput
receivedFlag = randi([obj.MinTput 100]) <= tput;
if receivedFlag
numReceivedSignal = numReceivedSignal+1;
bsmOut.IsValidTime = true;
bsmOut.BSMCoreData(bsmOutIdx) = bsm.BSMCoreData(i);
bsmOutIdx = bsmOutIdx+1;
end
end
end
bsmOut.NumOfBSM = numReceivedSignal;
end
function bsmOut = getOutputSizeImpl(obj) %#ok<MANU>
% Return size for each output port
bsmOut = 1;
end
function bsmOut = getOutputDataTypeImpl(obj) %#ok<MANU>
% Return data type for each output port
bsmOut = ‘BusBSM’;
end
function bsmOut = isOutputComplexImpl(obj) %#ok<MANU>
% Return true for each output port with complex data
bsmOut = false;
end
function bsmOut = isOutputFixedSizeImpl(obj) %#ok<MANU>
% Return true for each output port with fixed size
bsmOut = true;
end
end
methods(Access = protected, Static)
function flag = showSimulateUsingImpl
% Return false if simulation mode hidden in System block dialog
flag = true;
end
end
end
I would like to obtain the receivedFlag value from the HelperV2VReceiver code in the Follower1 Simulink example and plot it in platooning.mlx. What should I do? simulink, roadrunner, matlab MATLAB Answers — New Questions
trainnet gives training loss is NaN
Hello, I’m currently working on semantic segmentation with Unet architecture on matlab. As version R2024a, I tried to train my model with the trainnet command. But after I ran my script, it gives me this result in Command Window.
I tried to change the MiniBatchSize and MaxEpoch but none seem to be working, it seemed like the training never happened because my GPU doesn’t seem to have any activity. Does anyone know how to resolve this? Is Matlab R2024a still buggy so this happens?Hello, I’m currently working on semantic segmentation with Unet architecture on matlab. As version R2024a, I tried to train my model with the trainnet command. But after I ran my script, it gives me this result in Command Window.
I tried to change the MiniBatchSize and MaxEpoch but none seem to be working, it seemed like the training never happened because my GPU doesn’t seem to have any activity. Does anyone know how to resolve this? Is Matlab R2024a still buggy so this happens? Hello, I’m currently working on semantic segmentation with Unet architecture on matlab. As version R2024a, I tried to train my model with the trainnet command. But after I ran my script, it gives me this result in Command Window.
I tried to change the MiniBatchSize and MaxEpoch but none seem to be working, it seemed like the training never happened because my GPU doesn’t seem to have any activity. Does anyone know how to resolve this? Is Matlab R2024a still buggy so this happens? deep learning MATLAB Answers — New Questions
Set vector direction to point away from a closed surface (or a point coordinate)?
Dear all,
I am plotting a closed potato-shaped surface using "patch", then adding some tangent planes using
plane=surf(x,y,z)
But when I am plotting the normals of those planes, using
normals=plane.FaceNormals
some of them are pointing "inwards" towards the potato, while others point outward away from it. How can I make them all point away from the surface (or the center) of the potato?
Thank you kindly!Dear all,
I am plotting a closed potato-shaped surface using "patch", then adding some tangent planes using
plane=surf(x,y,z)
But when I am plotting the normals of those planes, using
normals=plane.FaceNormals
some of them are pointing "inwards" towards the potato, while others point outward away from it. How can I make them all point away from the surface (or the center) of the potato?
Thank you kindly! Dear all,
I am plotting a closed potato-shaped surface using "patch", then adding some tangent planes using
plane=surf(x,y,z)
But when I am plotting the normals of those planes, using
normals=plane.FaceNormals
some of them are pointing "inwards" towards the potato, while others point outward away from it. How can I make them all point away from the surface (or the center) of the potato?
Thank you kindly! surf, patch, normal vectors MATLAB Answers — New Questions
Modeling a pde on matlab
How do I model the given pde on matlabHow do I model the given pde on matlab How do I model the given pde on matlab pde MATLAB Answers — New Questions
How to manually edit located peaks using findpeaks function?
I’m trying to use findpeaks to localize R peaks from electrocardiogram signal. I’m getting good results but there are some missing and false positive peaks. So, I would like to know if there is an option to manually edit the located peaks. If it is not possible to manually edit the data I would be glad reciving any other suggestion. Thanks.I’m trying to use findpeaks to localize R peaks from electrocardiogram signal. I’m getting good results but there are some missing and false positive peaks. So, I would like to know if there is an option to manually edit the located peaks. If it is not possible to manually edit the data I would be glad reciving any other suggestion. Thanks. I’m trying to use findpeaks to localize R peaks from electrocardiogram signal. I’m getting good results but there are some missing and false positive peaks. So, I would like to know if there is an option to manually edit the located peaks. If it is not possible to manually edit the data I would be glad reciving any other suggestion. Thanks. manually edit peaks, findpeaks, missing peaks MATLAB Answers — New Questions
Save struct field names with hyphens/dash in JSON?
It is quite common to use hyphens/dashes (-) in the field names of JSON, like this:
{
"file-series-version" : "1.0",
"files" : [
{ "name" : "foo1.vtk", "time" : 0 },
{ "name" : "foo2.vtk", "time" : 5.5 },
{ "name" : "foo3.vtk", "time" : 11.2 }
]
}
However, I haven’t found a way to get a hyphen character into the JSON with the JSON encoder https://se.mathworks.com/help/matlab/ref/jsonencode.html as that has to be done through the field names of a struct, incorrectly like this
jsonObj = struct(‘file-series-version’, 1); % This will generate ‘Invalid field name "file-series-version".’
jsonencode(jsonObj)
So, is there any standardized way of creating these kind of JSON objects with the jsonencode function? My alternative would be to use camelCase on the field names, and regex over the JSON-string after encoding to convert them into kebab-case, but that is not a generally good idea.It is quite common to use hyphens/dashes (-) in the field names of JSON, like this:
{
"file-series-version" : "1.0",
"files" : [
{ "name" : "foo1.vtk", "time" : 0 },
{ "name" : "foo2.vtk", "time" : 5.5 },
{ "name" : "foo3.vtk", "time" : 11.2 }
]
}
However, I haven’t found a way to get a hyphen character into the JSON with the JSON encoder https://se.mathworks.com/help/matlab/ref/jsonencode.html as that has to be done through the field names of a struct, incorrectly like this
jsonObj = struct(‘file-series-version’, 1); % This will generate ‘Invalid field name "file-series-version".’
jsonencode(jsonObj)
So, is there any standardized way of creating these kind of JSON objects with the jsonencode function? My alternative would be to use camelCase on the field names, and regex over the JSON-string after encoding to convert them into kebab-case, but that is not a generally good idea. It is quite common to use hyphens/dashes (-) in the field names of JSON, like this:
{
"file-series-version" : "1.0",
"files" : [
{ "name" : "foo1.vtk", "time" : 0 },
{ "name" : "foo2.vtk", "time" : 5.5 },
{ "name" : "foo3.vtk", "time" : 11.2 }
]
}
However, I haven’t found a way to get a hyphen character into the JSON with the JSON encoder https://se.mathworks.com/help/matlab/ref/jsonencode.html as that has to be done through the field names of a struct, incorrectly like this
jsonObj = struct(‘file-series-version’, 1); % This will generate ‘Invalid field name "file-series-version".’
jsonencode(jsonObj)
So, is there any standardized way of creating these kind of JSON objects with the jsonencode function? My alternative would be to use camelCase on the field names, and regex over the JSON-string after encoding to convert them into kebab-case, but that is not a generally good idea. json hyphen dash MATLAB Answers — New Questions
Matlab run_functional test r2022a is failing with “unrecognized function or variable ‘ippl'”
Matlab test suite r2021b is passing but when we run r2022a, run_functional.m fails almost immediately with the error message in the Summary. Here is the code where the issue is found at the beginning of run_functional.
%% Show info about IPP
[isIPPOn, ippVersion] = ippl; disp(‘IPP enabled: ‘); disp(isIPPOn); disp(‘IPP version:’); disp(ippVersion);
Has the function ippl been replaced by another function to detect the presence of Intel® Integrated Performance Primitives on the test system?Matlab test suite r2021b is passing but when we run r2022a, run_functional.m fails almost immediately with the error message in the Summary. Here is the code where the issue is found at the beginning of run_functional.
%% Show info about IPP
[isIPPOn, ippVersion] = ippl; disp(‘IPP enabled: ‘); disp(isIPPOn); disp(‘IPP version:’); disp(ippVersion);
Has the function ippl been replaced by another function to detect the presence of Intel® Integrated Performance Primitives on the test system? Matlab test suite r2021b is passing but when we run r2022a, run_functional.m fails almost immediately with the error message in the Summary. Here is the code where the issue is found at the beginning of run_functional.
%% Show info about IPP
[isIPPOn, ippVersion] = ippl; disp(‘IPP enabled: ‘); disp(isIPPOn); disp(‘IPP version:’); disp(ippVersion);
Has the function ippl been replaced by another function to detect the presence of Intel® Integrated Performance Primitives on the test system? r2022a MATLAB Answers — New Questions
Where can I find a good example of using tied weights in nested layers?
I could use some guidance on how to use tied weights for an autoencoder. The example provided in the documentation throws several errors within the dlnetwork object it uses. I would appreciate an-up-to-date example of weight tying or guidance on how to update the MathWorks example to function again.I could use some guidance on how to use tied weights for an autoencoder. The example provided in the documentation throws several errors within the dlnetwork object it uses. I would appreciate an-up-to-date example of weight tying or guidance on how to update the MathWorks example to function again. I could use some guidance on how to use tied weights for an autoencoder. The example provided in the documentation throws several errors within the dlnetwork object it uses. I would appreciate an-up-to-date example of weight tying or guidance on how to update the MathWorks example to function again. deep learning, weight-tying, nested networks MATLAB Answers — New Questions
Analyze MIMIC III waveform data directly in Matlab
I would like to analyze MIMIC III waveform data (mainly PPG and ABP) directly in Matlab on a MacOS without going through Google or AWS database queries. Has anyone done this? Can you advise me on the best way?
Thanks
RamI would like to analyze MIMIC III waveform data (mainly PPG and ABP) directly in Matlab on a MacOS without going through Google or AWS database queries. Has anyone done this? Can you advise me on the best way?
Thanks
Ram I would like to analyze MIMIC III waveform data (mainly PPG and ABP) directly in Matlab on a MacOS without going through Google or AWS database queries. Has anyone done this? Can you advise me on the best way?
Thanks
Ram mimic MATLAB Answers — New Questions
i have a csv with data separated with commas and columns also are separated with commas
example of one line of my csv [6,75000e-003,0,00000e+000,6,75000e-003,0,00000e+000,6,75000e-003,0,00000e+000,]
i am usin this:
M=readmatrix(‘piloto.csv’);
M2=readtable(‘piloto.csv’);
but the values are separated alsoexample of one line of my csv [6,75000e-003,0,00000e+000,6,75000e-003,0,00000e+000,6,75000e-003,0,00000e+000,]
i am usin this:
M=readmatrix(‘piloto.csv’);
M2=readtable(‘piloto.csv’);
but the values are separated also example of one line of my csv [6,75000e-003,0,00000e+000,6,75000e-003,0,00000e+000,6,75000e-003,0,00000e+000,]
i am usin this:
M=readmatrix(‘piloto.csv’);
M2=readtable(‘piloto.csv’);
but the values are separated also readmatrix, readtable, commas MATLAB Answers — New Questions
Can I plot S21 and S12 from .s1p data?
In a first set of measurements from my VNA (vector network analyser), I was able to collect .s2p files which I could plot the S-parameters from. In a later set of measurements, I somehow only had the option to save the files as either .s1p. Can I not gain the S21 and s12 plots from these? Matlab won’t let me import the data either, is this something that Matlab is not designed to do or am I doing something wrong?In a first set of measurements from my VNA (vector network analyser), I was able to collect .s2p files which I could plot the S-parameters from. In a later set of measurements, I somehow only had the option to save the files as either .s1p. Can I not gain the S21 and s12 plots from these? Matlab won’t let me import the data either, is this something that Matlab is not designed to do or am I doing something wrong? In a first set of measurements from my VNA (vector network analyser), I was able to collect .s2p files which I could plot the S-parameters from. In a later set of measurements, I somehow only had the option to save the files as either .s1p. Can I not gain the S21 and s12 plots from these? Matlab won’t let me import the data either, is this something that Matlab is not designed to do or am I doing something wrong? s-parameters, scattering parameters, vna data, vector network analyser data, .s1p MATLAB Answers — New Questions
randperm function for a table – keep rows together
I looked in help but everone seems to be randomizing a vector.
The closest ask I can find is
https://www.mathworks.com/matlabcentral/answers/155207-matrix-with-different-randperm-rows?s_tid=sug_su
I have a table (including a category column) I asked (Q )about using Shuffle but if that doesn’t handle table shuffling like I need i can take the performance hit and use randperm()
Here’s what I’m doing:
app.TrialsTable = table(‘Size’,[2*C 4],’VariableTypes’,{‘uint8′,’uint8′,’categorical’,’int16′});
… % fill the table from given input table, expanding rows as needed for number of repeats
app.TrialsTable(index, 1) = … %and so on
…
app.TrialsTable = Shuffle(app.TrialsTable, ???); % if anyone knows how to do it this way
& or
app.TrialsTable(randperm(height(app.TrialsTable(:,:)))); % How do I make this line work??
% and then finally
set(app.RandTrialsTable,’Data’,app.TrialsTable(:,:)); % save it to the UITable for display in the Figure
Testing at the command prompt for various options of randperm(…)
app.TrialsTable(randperm(height(app.TrialsTable(:,:))))
Error using ()
Subscripting into a table using one subscript (as in t(i)) is not supported. Specify
a row subscript and a variable subscript, as in t(rows,vars). To select variables,
use t(:,i) or for one variable t.(i). To select rows, use t(i,:).
I didn’t use 1 subscript so the Error message doesn’t help
Another try:
app.TrialsTable(:,:)(randperm(height(app.TrialsTable(:,:))))
Error: Invalid array indexing.
Test
(randperm(height(app.TrialsTable(:,:))))
ans =
Columns 1 through 14
17 18 13 8 3 9 19 27 14 6 25 15 2 5
Columns 15 through 28
7 23 24 12 22 20 28 21 26 4 16 1 10 11
I only have 4 columns (28 rows)
Try
(randperm(height(app.TrialsTable)))
ans =
Columns 1 through 14
27 14 22 4 10 2 21 3 5 15 18 28 23 7
Columns 15 through 28
24 16 25 9 6 13 26 17 19 20 1 11 8 12
No sign of the category column (‘L’ or ‘R’) sorting along with it.
OH! maybe I don’t need to tell the height (as the Shuffle guy said)
(randperm(app.TrialsTable))
Error using randperm
Conversion to double from table is not possible.
try
(randperm(app.TrialsTable(:,:)))
Error using randperm
Conversion to double from table is not possible.
randperm(1:size(app.TrialsTable.Row))
ans =
1×0 empty double row vector
I tried on my own, time to ask for help!I looked in help but everone seems to be randomizing a vector.
The closest ask I can find is
https://www.mathworks.com/matlabcentral/answers/155207-matrix-with-different-randperm-rows?s_tid=sug_su
I have a table (including a category column) I asked (Q )about using Shuffle but if that doesn’t handle table shuffling like I need i can take the performance hit and use randperm()
Here’s what I’m doing:
app.TrialsTable = table(‘Size’,[2*C 4],’VariableTypes’,{‘uint8′,’uint8′,’categorical’,’int16′});
… % fill the table from given input table, expanding rows as needed for number of repeats
app.TrialsTable(index, 1) = … %and so on
…
app.TrialsTable = Shuffle(app.TrialsTable, ???); % if anyone knows how to do it this way
& or
app.TrialsTable(randperm(height(app.TrialsTable(:,:)))); % How do I make this line work??
% and then finally
set(app.RandTrialsTable,’Data’,app.TrialsTable(:,:)); % save it to the UITable for display in the Figure
Testing at the command prompt for various options of randperm(…)
app.TrialsTable(randperm(height(app.TrialsTable(:,:))))
Error using ()
Subscripting into a table using one subscript (as in t(i)) is not supported. Specify
a row subscript and a variable subscript, as in t(rows,vars). To select variables,
use t(:,i) or for one variable t.(i). To select rows, use t(i,:).
I didn’t use 1 subscript so the Error message doesn’t help
Another try:
app.TrialsTable(:,:)(randperm(height(app.TrialsTable(:,:))))
Error: Invalid array indexing.
Test
(randperm(height(app.TrialsTable(:,:))))
ans =
Columns 1 through 14
17 18 13 8 3 9 19 27 14 6 25 15 2 5
Columns 15 through 28
7 23 24 12 22 20 28 21 26 4 16 1 10 11
I only have 4 columns (28 rows)
Try
(randperm(height(app.TrialsTable)))
ans =
Columns 1 through 14
27 14 22 4 10 2 21 3 5 15 18 28 23 7
Columns 15 through 28
24 16 25 9 6 13 26 17 19 20 1 11 8 12
No sign of the category column (‘L’ or ‘R’) sorting along with it.
OH! maybe I don’t need to tell the height (as the Shuffle guy said)
(randperm(app.TrialsTable))
Error using randperm
Conversion to double from table is not possible.
try
(randperm(app.TrialsTable(:,:)))
Error using randperm
Conversion to double from table is not possible.
randperm(1:size(app.TrialsTable.Row))
ans =
1×0 empty double row vector
I tried on my own, time to ask for help! I looked in help but everone seems to be randomizing a vector.
The closest ask I can find is
https://www.mathworks.com/matlabcentral/answers/155207-matrix-with-different-randperm-rows?s_tid=sug_su
I have a table (including a category column) I asked (Q )about using Shuffle but if that doesn’t handle table shuffling like I need i can take the performance hit and use randperm()
Here’s what I’m doing:
app.TrialsTable = table(‘Size’,[2*C 4],’VariableTypes’,{‘uint8′,’uint8′,’categorical’,’int16′});
… % fill the table from given input table, expanding rows as needed for number of repeats
app.TrialsTable(index, 1) = … %and so on
…
app.TrialsTable = Shuffle(app.TrialsTable, ???); % if anyone knows how to do it this way
& or
app.TrialsTable(randperm(height(app.TrialsTable(:,:)))); % How do I make this line work??
% and then finally
set(app.RandTrialsTable,’Data’,app.TrialsTable(:,:)); % save it to the UITable for display in the Figure
Testing at the command prompt for various options of randperm(…)
app.TrialsTable(randperm(height(app.TrialsTable(:,:))))
Error using ()
Subscripting into a table using one subscript (as in t(i)) is not supported. Specify
a row subscript and a variable subscript, as in t(rows,vars). To select variables,
use t(:,i) or for one variable t.(i). To select rows, use t(i,:).
I didn’t use 1 subscript so the Error message doesn’t help
Another try:
app.TrialsTable(:,:)(randperm(height(app.TrialsTable(:,:))))
Error: Invalid array indexing.
Test
(randperm(height(app.TrialsTable(:,:))))
ans =
Columns 1 through 14
17 18 13 8 3 9 19 27 14 6 25 15 2 5
Columns 15 through 28
7 23 24 12 22 20 28 21 26 4 16 1 10 11
I only have 4 columns (28 rows)
Try
(randperm(height(app.TrialsTable)))
ans =
Columns 1 through 14
27 14 22 4 10 2 21 3 5 15 18 28 23 7
Columns 15 through 28
24 16 25 9 6 13 26 17 19 20 1 11 8 12
No sign of the category column (‘L’ or ‘R’) sorting along with it.
OH! maybe I don’t need to tell the height (as the Shuffle guy said)
(randperm(app.TrialsTable))
Error using randperm
Conversion to double from table is not possible.
try
(randperm(app.TrialsTable(:,:)))
Error using randperm
Conversion to double from table is not possible.
randperm(1:size(app.TrialsTable.Row))
ans =
1×0 empty double row vector
I tried on my own, time to ask for help! shuffling a table MATLAB Answers — New Questions
Adding a global legend to a tiledlayout
Good morning,
I’m using MATLAB R2020a Update 2. I have a tiledlayout of five (three by two) area plots and would like to use the sixth, currently empty, tile to add a global legend. I’ve already found this question, and understand that there’s no official, built-in way of doing this, but perhaps it’s possible to get creative.
What I’ve tried is adding a new, empty area plot to the sixth tile, using NaNs as the shares, then adding a legend to that and setting the axis object for that tile to invisible, as follows:
% …
ax = nexttile;
area([NaN NaN], NaN(2, 4));
leg = legend({‘tar’, ‘sta’, ‘ext’, ‘dmp’);
leg.Location = ‘none’;
leg.Interpreter = ‘latex’;
leg.FontSize = 16;
ax.Visible = false;
This works in principle, but leaves a horizontal line where the X axis would be:
This only happens when I use area(), not e.g. plot(). Perhaps it’s a bug, perhaps it’s intentional and due to the way area() works. In any case it’s not what I want, but I can’t get rid of it (without breaking other things in the process).
I had the idea of making the children of this axis, i.e. the areas of the area plot, invisible as well, like so:
for i = 1:length(ax.Children)
ax.Children(i).Visible = false;
end
But while this gets rid of the horizontal line it also grays out the legend entries:
This behavior in turn is known and expected and apparently cannot be changed. The workaround suggested by a Mathworks staffer in the linked question is to plot NaNs; but that’s what I’m already doing and what’s leaving the horizontal line, due to area()’s quirks.
Can anyone help?
I’m not hung up on specifically creating an invisible area(), this is merely the best (first, only) idea I had for fudging a global legend. If anyone can make this approach work, that’d be wonderful. If anyone has another idea of how to achieve a similar effect, that’d be wonderful as well.
Thank you very much!Good morning,
I’m using MATLAB R2020a Update 2. I have a tiledlayout of five (three by two) area plots and would like to use the sixth, currently empty, tile to add a global legend. I’ve already found this question, and understand that there’s no official, built-in way of doing this, but perhaps it’s possible to get creative.
What I’ve tried is adding a new, empty area plot to the sixth tile, using NaNs as the shares, then adding a legend to that and setting the axis object for that tile to invisible, as follows:
% …
ax = nexttile;
area([NaN NaN], NaN(2, 4));
leg = legend({‘tar’, ‘sta’, ‘ext’, ‘dmp’);
leg.Location = ‘none’;
leg.Interpreter = ‘latex’;
leg.FontSize = 16;
ax.Visible = false;
This works in principle, but leaves a horizontal line where the X axis would be:
This only happens when I use area(), not e.g. plot(). Perhaps it’s a bug, perhaps it’s intentional and due to the way area() works. In any case it’s not what I want, but I can’t get rid of it (without breaking other things in the process).
I had the idea of making the children of this axis, i.e. the areas of the area plot, invisible as well, like so:
for i = 1:length(ax.Children)
ax.Children(i).Visible = false;
end
But while this gets rid of the horizontal line it also grays out the legend entries:
This behavior in turn is known and expected and apparently cannot be changed. The workaround suggested by a Mathworks staffer in the linked question is to plot NaNs; but that’s what I’m already doing and what’s leaving the horizontal line, due to area()’s quirks.
Can anyone help?
I’m not hung up on specifically creating an invisible area(), this is merely the best (first, only) idea I had for fudging a global legend. If anyone can make this approach work, that’d be wonderful. If anyone has another idea of how to achieve a similar effect, that’d be wonderful as well.
Thank you very much! Good morning,
I’m using MATLAB R2020a Update 2. I have a tiledlayout of five (three by two) area plots and would like to use the sixth, currently empty, tile to add a global legend. I’ve already found this question, and understand that there’s no official, built-in way of doing this, but perhaps it’s possible to get creative.
What I’ve tried is adding a new, empty area plot to the sixth tile, using NaNs as the shares, then adding a legend to that and setting the axis object for that tile to invisible, as follows:
% …
ax = nexttile;
area([NaN NaN], NaN(2, 4));
leg = legend({‘tar’, ‘sta’, ‘ext’, ‘dmp’);
leg.Location = ‘none’;
leg.Interpreter = ‘latex’;
leg.FontSize = 16;
ax.Visible = false;
This works in principle, but leaves a horizontal line where the X axis would be:
This only happens when I use area(), not e.g. plot(). Perhaps it’s a bug, perhaps it’s intentional and due to the way area() works. In any case it’s not what I want, but I can’t get rid of it (without breaking other things in the process).
I had the idea of making the children of this axis, i.e. the areas of the area plot, invisible as well, like so:
for i = 1:length(ax.Children)
ax.Children(i).Visible = false;
end
But while this gets rid of the horizontal line it also grays out the legend entries:
This behavior in turn is known and expected and apparently cannot be changed. The workaround suggested by a Mathworks staffer in the linked question is to plot NaNs; but that’s what I’m already doing and what’s leaving the horizontal line, due to area()’s quirks.
Can anyone help?
I’m not hung up on specifically creating an invisible area(), this is merely the best (first, only) idea I had for fudging a global legend. If anyone can make this approach work, that’d be wonderful. If anyone has another idea of how to achieve a similar effect, that’d be wonderful as well.
Thank you very much! tiledlayout, legend MATLAB Answers — New Questions
Improving Simulation Speed in Simulink Using C language (mexw64 File) for DC/DC Converters
I have a question regarding speeding up the simulation using Simulink and a compiled C language mexw64 file. Suppose I have 8 DC/DC converters, each controlled by a dual-loop control strategy, and the control of each converter is independent. How can I use the mexw64 file to achieve the fastest simulation speed? I am mainly comparing the following two scenarios:
Input the data of all 8 converters into a single s-function module containing the mexw64 file. In C language, set 8 groups of control parameters with the same structure, and use one mexw64 file to output the duty cycles for all 8 converters, as shown in the figure below.
Fig. 1 simulink and C code
Use 8 separate s-function modules, each containing the same mexw64 file, with each s-function module calculating the duty cycle of its respective converter, as shown in the figure below.
Fig. 2
Which scenario will result in faster simulation speed? Thank you for your assistance.I have a question regarding speeding up the simulation using Simulink and a compiled C language mexw64 file. Suppose I have 8 DC/DC converters, each controlled by a dual-loop control strategy, and the control of each converter is independent. How can I use the mexw64 file to achieve the fastest simulation speed? I am mainly comparing the following two scenarios:
Input the data of all 8 converters into a single s-function module containing the mexw64 file. In C language, set 8 groups of control parameters with the same structure, and use one mexw64 file to output the duty cycles for all 8 converters, as shown in the figure below.
Fig. 1 simulink and C code
Use 8 separate s-function modules, each containing the same mexw64 file, with each s-function module calculating the duty cycle of its respective converter, as shown in the figure below.
Fig. 2
Which scenario will result in faster simulation speed? Thank you for your assistance. I have a question regarding speeding up the simulation using Simulink and a compiled C language mexw64 file. Suppose I have 8 DC/DC converters, each controlled by a dual-loop control strategy, and the control of each converter is independent. How can I use the mexw64 file to achieve the fastest simulation speed? I am mainly comparing the following two scenarios:
Input the data of all 8 converters into a single s-function module containing the mexw64 file. In C language, set 8 groups of control parameters with the same structure, and use one mexw64 file to output the duty cycles for all 8 converters, as shown in the figure below.
Fig. 1 simulink and C code
Use 8 separate s-function modules, each containing the same mexw64 file, with each s-function module calculating the duty cycle of its respective converter, as shown in the figure below.
Fig. 2
Which scenario will result in faster simulation speed? Thank you for your assistance. simulink, s-function, c code MATLAB Answers — New Questions
How can I turn off the automatic import of file logs from my Speedgoat target?
I am using File Log blocks in my Simulink Real-Time (SLRT) model (available since R2020b) to log data on the Speedgoat target computer file system. After the real-time application stops, if the development computer running MATLAB is connected to the Speedgoat, File Log data is automatically transferred and loaded on the Simulation Data Inspector (SDI).
What are the different ways to turn off this auto-import behavior for File Logs?I am using File Log blocks in my Simulink Real-Time (SLRT) model (available since R2020b) to log data on the Speedgoat target computer file system. After the real-time application stops, if the development computer running MATLAB is connected to the Speedgoat, File Log data is automatically transferred and loaded on the Simulation Data Inspector (SDI).
What are the different ways to turn off this auto-import behavior for File Logs? I am using File Log blocks in my Simulink Real-Time (SLRT) model (available since R2020b) to log data on the Speedgoat target computer file system. After the real-time application stops, if the development computer running MATLAB is connected to the Speedgoat, File Log data is automatically transferred and loaded on the Simulation Data Inspector (SDI).
What are the different ways to turn off this auto-import behavior for File Logs? autoimportfilelog, filelog MATLAB Answers — New Questions
Highlight certain regions where the value goes to 0 in Stacked Plot
Hi, can we highlight certain regions in stackplot where the value of a certain variable goes to zero.
I currently have
p1=stackedplot(final_log(:,["TC2","Ftot"]));
I want to highlight cerain areah where Ftot goes to Zero
Thank you.Hi, can we highlight certain regions in stackplot where the value of a certain variable goes to zero.
I currently have
p1=stackedplot(final_log(:,["TC2","Ftot"]));
I want to highlight cerain areah where Ftot goes to Zero
Thank you. Hi, can we highlight certain regions in stackplot where the value of a certain variable goes to zero.
I currently have
p1=stackedplot(final_log(:,["TC2","Ftot"]));
I want to highlight cerain areah where Ftot goes to Zero
Thank you. stackedplot MATLAB Answers — New Questions
Solving unknown matrics to the power 20
% [P] * [TPM]^n* [R]= CR
disp(‘Create an array with seven elements in a single row:’)
disp(‘>> P = [1 0 0 0 0 0 0]’)
p = [1 0 0 0 0 0 0]
disp(‘Create an array with seven elements in a single column:’)
disp(‘>> R = [9; 8; 7; 6; 5; 4; 3]’)
R = [9; 8; 7; 6; 5; 4; 3]
CR = [0.45]
Solve (TPM)^20=CR/ (p*R)
I would like to find the matrics [TPM] with size 7*7? How to do it ?% [P] * [TPM]^n* [R]= CR
disp(‘Create an array with seven elements in a single row:’)
disp(‘>> P = [1 0 0 0 0 0 0]’)
p = [1 0 0 0 0 0 0]
disp(‘Create an array with seven elements in a single column:’)
disp(‘>> R = [9; 8; 7; 6; 5; 4; 3]’)
R = [9; 8; 7; 6; 5; 4; 3]
CR = [0.45]
Solve (TPM)^20=CR/ (p*R)
I would like to find the matrics [TPM] with size 7*7? How to do it ? % [P] * [TPM]^n* [R]= CR
disp(‘Create an array with seven elements in a single row:’)
disp(‘>> P = [1 0 0 0 0 0 0]’)
p = [1 0 0 0 0 0 0]
disp(‘Create an array with seven elements in a single column:’)
disp(‘>> R = [9; 8; 7; 6; 5; 4; 3]’)
R = [9; 8; 7; 6; 5; 4; 3]
CR = [0.45]
Solve (TPM)^20=CR/ (p*R)
I would like to find the matrics [TPM] with size 7*7? How to do it ? matrix, solve, equation, matrix manipulation, matrix array, matrices, matlab, mathematics MATLAB Answers — New Questions
How do I download gstreamer into matlab, it is on my computer
I have started out with MATLAB, I have installed psychtoolbox and have downloaded it into MATLAB, I have got gstreamer onto my laptop but having trouble to know what to do next to get it into MATLAB also so I can start to create graphics using all 3 together, MATLAB, with psychtoolbox and gstreamer. I need to donthis so I can start going throug( my tutorials with PTBI have started out with MATLAB, I have installed psychtoolbox and have downloaded it into MATLAB, I have got gstreamer onto my laptop but having trouble to know what to do next to get it into MATLAB also so I can start to create graphics using all 3 together, MATLAB, with psychtoolbox and gstreamer. I need to donthis so I can start going throug( my tutorials with PTB I have started out with MATLAB, I have installed psychtoolbox and have downloaded it into MATLAB, I have got gstreamer onto my laptop but having trouble to know what to do next to get it into MATLAB also so I can start to create graphics using all 3 together, MATLAB, with psychtoolbox and gstreamer. I need to donthis so I can start going throug( my tutorials with PTB gstreamer psychtoolbox, installation. MATLAB Answers — New Questions
Use of eig(A) for eigenvectors
Hi, I try to call the eigenvectors of the respective eigenvalue, but that part in the code gives an error:
"Unrecognize function or variable ‘eigvecs_theta’
I tried eig and eigvec instead of eigvecs_theta, but nothing works. What did I miss here? Thanks
% Discretization parameters
theta_min = 0;
theta_max = pi;
M = 100; % Number of grid points
theta = linspace(theta_min, theta_max, M);
dtheta = theta(2) – theta(1);
% Initialize the Theta(theta) vector
Theta = zeros(M, 1);
% Set up the finite difference matrix
B = zeros(M, M);
for j = 3:M-2
B(j, j-2) = -1 / (2 * dtheta^3);
B(j, j-1) = 2 / (dtheta^3);
B(j, j) = -2 / (dtheta^3) + l * (l + 1);
B(j, j+1) = 2 / (dtheta^3);
B(j, j+2) = -1 / (2 * dtheta^3);
end
% Apply boundary conditions (example: Theta(0) = 0 and Theta(pi) = 0)
B(1,1) = 1;
B(M,M) = 1;
% Solve the eigenvalue problem
[~, D_theta] = eig(B);
% The eigenvalues are the diagonal elements of D_theta
eigenvalues_theta = diag(D_theta);
% The solution Theta(theta) corresponds to the eigenvector with the desired eigenvalue
Theta = eig(:, idx);
% Plot the solution
plot(theta, Theta);
xlabel(‘theta’);
ylabel(‘Theta(theta)’);
title(‘Angular Wavefunction’);
endHi, I try to call the eigenvectors of the respective eigenvalue, but that part in the code gives an error:
"Unrecognize function or variable ‘eigvecs_theta’
I tried eig and eigvec instead of eigvecs_theta, but nothing works. What did I miss here? Thanks
% Discretization parameters
theta_min = 0;
theta_max = pi;
M = 100; % Number of grid points
theta = linspace(theta_min, theta_max, M);
dtheta = theta(2) – theta(1);
% Initialize the Theta(theta) vector
Theta = zeros(M, 1);
% Set up the finite difference matrix
B = zeros(M, M);
for j = 3:M-2
B(j, j-2) = -1 / (2 * dtheta^3);
B(j, j-1) = 2 / (dtheta^3);
B(j, j) = -2 / (dtheta^3) + l * (l + 1);
B(j, j+1) = 2 / (dtheta^3);
B(j, j+2) = -1 / (2 * dtheta^3);
end
% Apply boundary conditions (example: Theta(0) = 0 and Theta(pi) = 0)
B(1,1) = 1;
B(M,M) = 1;
% Solve the eigenvalue problem
[~, D_theta] = eig(B);
% The eigenvalues are the diagonal elements of D_theta
eigenvalues_theta = diag(D_theta);
% The solution Theta(theta) corresponds to the eigenvector with the desired eigenvalue
Theta = eig(:, idx);
% Plot the solution
plot(theta, Theta);
xlabel(‘theta’);
ylabel(‘Theta(theta)’);
title(‘Angular Wavefunction’);
end Hi, I try to call the eigenvectors of the respective eigenvalue, but that part in the code gives an error:
"Unrecognize function or variable ‘eigvecs_theta’
I tried eig and eigvec instead of eigvecs_theta, but nothing works. What did I miss here? Thanks
% Discretization parameters
theta_min = 0;
theta_max = pi;
M = 100; % Number of grid points
theta = linspace(theta_min, theta_max, M);
dtheta = theta(2) – theta(1);
% Initialize the Theta(theta) vector
Theta = zeros(M, 1);
% Set up the finite difference matrix
B = zeros(M, M);
for j = 3:M-2
B(j, j-2) = -1 / (2 * dtheta^3);
B(j, j-1) = 2 / (dtheta^3);
B(j, j) = -2 / (dtheta^3) + l * (l + 1);
B(j, j+1) = 2 / (dtheta^3);
B(j, j+2) = -1 / (2 * dtheta^3);
end
% Apply boundary conditions (example: Theta(0) = 0 and Theta(pi) = 0)
B(1,1) = 1;
B(M,M) = 1;
% Solve the eigenvalue problem
[~, D_theta] = eig(B);
% The eigenvalues are the diagonal elements of D_theta
eigenvalues_theta = diag(D_theta);
% The solution Theta(theta) corresponds to the eigenvector with the desired eigenvalue
Theta = eig(:, idx);
% Plot the solution
plot(theta, Theta);
xlabel(‘theta’);
ylabel(‘Theta(theta)’);
title(‘Angular Wavefunction’);
end eigenvalues, eigenvectors MATLAB Answers — New Questions
Why are long integers inappropriate for switch expressions?
Why are long integers used in switch expressions (C99) flagged as a defect for being an inappropriate data type in Polyspace Bug Finder?
Matlab documentation only allows char, int, short or enum. Considering int can be either a 64 or 32 bit integer dependent on platform, it seems that a long, an explicit 32 bit integer, should be allowed.
Link to Matlab documentation of defect:
https://www.mathworks.com/help/bugfinder/ref/possiblyinappropriatedatatypeforswitchexpression.html
Example:
unsigned long x = 1u;
switch(x) // Defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
unsigned int y = 1u;
switch(y) // No defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
Thanks,
TommyWhy are long integers used in switch expressions (C99) flagged as a defect for being an inappropriate data type in Polyspace Bug Finder?
Matlab documentation only allows char, int, short or enum. Considering int can be either a 64 or 32 bit integer dependent on platform, it seems that a long, an explicit 32 bit integer, should be allowed.
Link to Matlab documentation of defect:
https://www.mathworks.com/help/bugfinder/ref/possiblyinappropriatedatatypeforswitchexpression.html
Example:
unsigned long x = 1u;
switch(x) // Defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
unsigned int y = 1u;
switch(y) // No defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
Thanks,
Tommy Why are long integers used in switch expressions (C99) flagged as a defect for being an inappropriate data type in Polyspace Bug Finder?
Matlab documentation only allows char, int, short or enum. Considering int can be either a 64 or 32 bit integer dependent on platform, it seems that a long, an explicit 32 bit integer, should be allowed.
Link to Matlab documentation of defect:
https://www.mathworks.com/help/bugfinder/ref/possiblyinappropriatedatatypeforswitchexpression.html
Example:
unsigned long x = 1u;
switch(x) // Defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
unsigned int y = 1u;
switch(y) // No defect
{
case 0u:
// do thing
break;
default:
// do thing
break;
}
Thanks,
Tommy polyspace, switch expression, data type, c99 MATLAB Answers — New Questions