Category: Matlab
Category Archives: Matlab
Code still functioning according to lines of code I have deleted
I’m trying to make a text box that the user can type into, which then retreives and prints that text when the user clicks enter. Two days ago it was working perfectly. Yesterday it stopped working properly. It prints the currently held text AND THEN updates with the what the user has input. So if I type in "bob" and click enter, nothing displays. If I delete "bob" and type in "peter", and click enter, it displays bob. Click enter again, and it displays "peter".
It got to the point that I just deleted the code and tried to start over. FOR SOME REASON, it still acts exactly the same, updating the text only when I click enter, despite the fact that I have no lines of code that refer to the enter key.
This is what I have right now:
function codeComponentResponse
fig = uifigure(‘position’,[2 50 637 641]);
TextArea = uieditfield(fig, ‘Position’,[100 100 500 30]);
fig.WindowKeyPressFcn = {@CoolGuy, fig, TextArea};
function CoolGuy(src, event, figure, field)
text = field.Value;
disp(text)
end
endI’m trying to make a text box that the user can type into, which then retreives and prints that text when the user clicks enter. Two days ago it was working perfectly. Yesterday it stopped working properly. It prints the currently held text AND THEN updates with the what the user has input. So if I type in "bob" and click enter, nothing displays. If I delete "bob" and type in "peter", and click enter, it displays bob. Click enter again, and it displays "peter".
It got to the point that I just deleted the code and tried to start over. FOR SOME REASON, it still acts exactly the same, updating the text only when I click enter, despite the fact that I have no lines of code that refer to the enter key.
This is what I have right now:
function codeComponentResponse
fig = uifigure(‘position’,[2 50 637 641]);
TextArea = uieditfield(fig, ‘Position’,[100 100 500 30]);
fig.WindowKeyPressFcn = {@CoolGuy, fig, TextArea};
function CoolGuy(src, event, figure, field)
text = field.Value;
disp(text)
end
end I’m trying to make a text box that the user can type into, which then retreives and prints that text when the user clicks enter. Two days ago it was working perfectly. Yesterday it stopped working properly. It prints the currently held text AND THEN updates with the what the user has input. So if I type in "bob" and click enter, nothing displays. If I delete "bob" and type in "peter", and click enter, it displays bob. Click enter again, and it displays "peter".
It got to the point that I just deleted the code and tried to start over. FOR SOME REASON, it still acts exactly the same, updating the text only when I click enter, despite the fact that I have no lines of code that refer to the enter key.
This is what I have right now:
function codeComponentResponse
fig = uifigure(‘position’,[2 50 637 641]);
TextArea = uieditfield(fig, ‘Position’,[100 100 500 30]);
fig.WindowKeyPressFcn = {@CoolGuy, fig, TextArea};
function CoolGuy(src, event, figure, field)
text = field.Value;
disp(text)
end
end uifigure, uieditfield, callback, text field MATLAB Answers — New Questions
How to interpolate at NaN values?
I have a vector [1 2 3 NaN 4 4.5 5.5 NaN NaN 6 6 7 NaN NaN NaN 8] and I want [1 2 3 3.5 4 4.5 5.5 5.75 5.75 6 6 7 7.5 7.5 7.5 8]. Is it possible to do this without a for cycle?I have a vector [1 2 3 NaN 4 4.5 5.5 NaN NaN 6 6 7 NaN NaN NaN 8] and I want [1 2 3 3.5 4 4.5 5.5 5.75 5.75 6 6 7 7.5 7.5 7.5 8]. Is it possible to do this without a for cycle? I have a vector [1 2 3 NaN 4 4.5 5.5 NaN NaN 6 6 7 NaN NaN NaN 8] and I want [1 2 3 3.5 4 4.5 5.5 5.75 5.75 6 6 7 7.5 7.5 7.5 8]. Is it possible to do this without a for cycle? for, vector, nan, interpolation MATLAB Answers — New Questions
Solving Eigenvalues of a system time-varying which is 5×5 matrix
I am trying to solve this system by using a desired eigenvalues to be equated to the det(SI-A) ,so every thing in that matrix is know except Lambda’s , I decoupled the problem by making eta_tilde=0 and then e =0 and I managed to obtain L and it was easier to get L in that way ,but the problem now is to obtain lambda that makes this matrix aysmptoically stable , SINCE it is linear time-varying w.r.t the error so according to lypunov it is better to check the stablity of (A^T+A) to place the eigenvalues to zero, it is complex to solve manually ,so I used the matlab to get the det(SI-A) symbolically ,but how to solve for lambda’s.I am trying to solve this system by using a desired eigenvalues to be equated to the det(SI-A) ,so every thing in that matrix is know except Lambda’s , I decoupled the problem by making eta_tilde=0 and then e =0 and I managed to obtain L and it was easier to get L in that way ,but the problem now is to obtain lambda that makes this matrix aysmptoically stable , SINCE it is linear time-varying w.r.t the error so according to lypunov it is better to check the stablity of (A^T+A) to place the eigenvalues to zero, it is complex to solve manually ,so I used the matlab to get the det(SI-A) symbolically ,but how to solve for lambda’s. I am trying to solve this system by using a desired eigenvalues to be equated to the det(SI-A) ,so every thing in that matrix is know except Lambda’s , I decoupled the problem by making eta_tilde=0 and then e =0 and I managed to obtain L and it was easier to get L in that way ,but the problem now is to obtain lambda that makes this matrix aysmptoically stable , SINCE it is linear time-varying w.r.t the error so according to lypunov it is better to check the stablity of (A^T+A) to place the eigenvalues to zero, it is complex to solve manually ,so I used the matlab to get the det(SI-A) symbolically ,but how to solve for lambda’s. #eigenvalues #stablity #ltv MATLAB Answers — New Questions
Filling a shape with Geoplot
I am creating a polygon using coordinate points with geoplot, and I would like to fill the resultant shape in a partially transparent blue color. I am able to create the filled shape, and I can overlay the outline on the map with geoplot, but I cannot do both.
%% Plot
% Create a figure
figure;
% Create a geographic axes
gx = geoaxes;
hold(gx, ‘on’);
% Define the indices of visible points
visibleIndices = maxRadiusPerAngle > 0;
% Close the loop by adding the first point at the end
latTargetsClosed = [latTargets(visibleIndices) latTargets(visibleIndices(1))];
lonTargetsClosed = [lonTargets(visibleIndices) lonTargets(visibleIndices(1))];
% Plot the outline of the polygon using geoplot
geoplot(gx, latTargetsClosed, lonTargetsClosed, ‘b-‘, ‘LineWidth’, 2);
% Plot the central point
geoplot(gx, latCenter, lonCenter, ‘ro’, ‘MarkerSize’, 8, ‘MarkerFaceColor’, ‘r’);
% Plot the visible points
geoplot(gx, latTargets(visibleIndices), lonTargets(visibleIndices), ‘go’, ‘MarkerSize’, 6, ‘MarkerFaceColor’, ‘g’);
% Set the basemap
geobasemap(gx, ‘streets’);
title(‘Furthest Outward Points with Positive LOS’);
% Define the Web Mercator projection
projCRS = projcrs(3857); % EPSG:3857 Web Mercator
% Convert geographic coordinates to projected coordinates
[x, y] = projfwd(projCRS, latTargetsClosed, lonTargetsClosed);
% Create a new Cartesian plot for the filled polygon, ensuring it overlays the geographic axes
figure;
hold on;
% Create a filled polygon in the Cartesian plot
fill(x, y, ‘b’, ‘FaceAlpha’, 0.3, ‘EdgeColor’, ‘none’);
% Set Cartesian axes limits to match the geographic plot
axis equal;
xlabel(‘X (meters)’);
ylabel(‘Y (meters)’);
title(‘Filled Polygon in Projected Coordinates’);
% Adjust the limits to fit the geographic plot
latlim = gx.LatitudeLimits;
lonlim = gx.LongitudeLimits;
[xlim, ylim] = projfwd(projCRS, [latlim(1), latlim(2)], [lonlim(1), lonlim(2)]);
set(gca, ‘XLim’, xlim, ‘YLim’, ylim);
% Ensure the Cartesian plot is visible
set(gcf, ‘Visible’, ‘on’);I am creating a polygon using coordinate points with geoplot, and I would like to fill the resultant shape in a partially transparent blue color. I am able to create the filled shape, and I can overlay the outline on the map with geoplot, but I cannot do both.
%% Plot
% Create a figure
figure;
% Create a geographic axes
gx = geoaxes;
hold(gx, ‘on’);
% Define the indices of visible points
visibleIndices = maxRadiusPerAngle > 0;
% Close the loop by adding the first point at the end
latTargetsClosed = [latTargets(visibleIndices) latTargets(visibleIndices(1))];
lonTargetsClosed = [lonTargets(visibleIndices) lonTargets(visibleIndices(1))];
% Plot the outline of the polygon using geoplot
geoplot(gx, latTargetsClosed, lonTargetsClosed, ‘b-‘, ‘LineWidth’, 2);
% Plot the central point
geoplot(gx, latCenter, lonCenter, ‘ro’, ‘MarkerSize’, 8, ‘MarkerFaceColor’, ‘r’);
% Plot the visible points
geoplot(gx, latTargets(visibleIndices), lonTargets(visibleIndices), ‘go’, ‘MarkerSize’, 6, ‘MarkerFaceColor’, ‘g’);
% Set the basemap
geobasemap(gx, ‘streets’);
title(‘Furthest Outward Points with Positive LOS’);
% Define the Web Mercator projection
projCRS = projcrs(3857); % EPSG:3857 Web Mercator
% Convert geographic coordinates to projected coordinates
[x, y] = projfwd(projCRS, latTargetsClosed, lonTargetsClosed);
% Create a new Cartesian plot for the filled polygon, ensuring it overlays the geographic axes
figure;
hold on;
% Create a filled polygon in the Cartesian plot
fill(x, y, ‘b’, ‘FaceAlpha’, 0.3, ‘EdgeColor’, ‘none’);
% Set Cartesian axes limits to match the geographic plot
axis equal;
xlabel(‘X (meters)’);
ylabel(‘Y (meters)’);
title(‘Filled Polygon in Projected Coordinates’);
% Adjust the limits to fit the geographic plot
latlim = gx.LatitudeLimits;
lonlim = gx.LongitudeLimits;
[xlim, ylim] = projfwd(projCRS, [latlim(1), latlim(2)], [lonlim(1), lonlim(2)]);
set(gca, ‘XLim’, xlim, ‘YLim’, ylim);
% Ensure the Cartesian plot is visible
set(gcf, ‘Visible’, ‘on’); I am creating a polygon using coordinate points with geoplot, and I would like to fill the resultant shape in a partially transparent blue color. I am able to create the filled shape, and I can overlay the outline on the map with geoplot, but I cannot do both.
%% Plot
% Create a figure
figure;
% Create a geographic axes
gx = geoaxes;
hold(gx, ‘on’);
% Define the indices of visible points
visibleIndices = maxRadiusPerAngle > 0;
% Close the loop by adding the first point at the end
latTargetsClosed = [latTargets(visibleIndices) latTargets(visibleIndices(1))];
lonTargetsClosed = [lonTargets(visibleIndices) lonTargets(visibleIndices(1))];
% Plot the outline of the polygon using geoplot
geoplot(gx, latTargetsClosed, lonTargetsClosed, ‘b-‘, ‘LineWidth’, 2);
% Plot the central point
geoplot(gx, latCenter, lonCenter, ‘ro’, ‘MarkerSize’, 8, ‘MarkerFaceColor’, ‘r’);
% Plot the visible points
geoplot(gx, latTargets(visibleIndices), lonTargets(visibleIndices), ‘go’, ‘MarkerSize’, 6, ‘MarkerFaceColor’, ‘g’);
% Set the basemap
geobasemap(gx, ‘streets’);
title(‘Furthest Outward Points with Positive LOS’);
% Define the Web Mercator projection
projCRS = projcrs(3857); % EPSG:3857 Web Mercator
% Convert geographic coordinates to projected coordinates
[x, y] = projfwd(projCRS, latTargetsClosed, lonTargetsClosed);
% Create a new Cartesian plot for the filled polygon, ensuring it overlays the geographic axes
figure;
hold on;
% Create a filled polygon in the Cartesian plot
fill(x, y, ‘b’, ‘FaceAlpha’, 0.3, ‘EdgeColor’, ‘none’);
% Set Cartesian axes limits to match the geographic plot
axis equal;
xlabel(‘X (meters)’);
ylabel(‘Y (meters)’);
title(‘Filled Polygon in Projected Coordinates’);
% Adjust the limits to fit the geographic plot
latlim = gx.LatitudeLimits;
lonlim = gx.LongitudeLimits;
[xlim, ylim] = projfwd(projCRS, [latlim(1), latlim(2)], [lonlim(1), lonlim(2)]);
set(gca, ‘XLim’, xlim, ‘YLim’, ylim);
% Ensure the Cartesian plot is visible
set(gcf, ‘Visible’, ‘on’); geoplot, mapping toolbox MATLAB Answers — New Questions
lsqcurvefit issues due to variables being several orders of magnitude different
I am trying to use lsqcurvefit to fit an equation to some data in order to solve for a couple variables. I have included the part of the code below that covers this. I am trying to solve for coeff(1) and coeff(2), The problem is that when I run lsqcurvefit, it is just using whatever my initial guesses are and outputting that as the solution. I suspect it is because my values for the coefficients will be several orders of magnitude different. You can kind of get an idea for this by looking at coeff0. Has anyone else run into this problem and/or do you know how to work around it? Any insight would be greatly appreciated.
load(‘V1.mat’)
load(‘Vp.mat’)
load(‘data.mat’)
V = [V1, Vp]; %voltages
a = 1.1792;
b = 0.5;
e = 1.60217662e-19;
Area = 4.7909e-7;
mi = 39.948./(6.022e23.*1000);
coeff0 = [7e10 4]; %initial guess
Eqn7 = @(coeff, VV) e^1.5*coeff(1)*Area*sqrt(coeff(2)/(2*pi*mi))*100^3*… (a*(-VV(:,1)/coeff(2)).^b.*tanh(VV(:,2)/(2*coeff(2))) + …
(a*(-VV(:,1)/coeff(2)).^b – a*(-(VV(:,1)+VV(:,2))/coeff(2)).^b)./(exp(VV(:,2)/coeff(2))+1);
options = optimoptions(‘lsqcurvefit’,’Algorithm’,’levenberg-marquardt’,’OptimalityTolerance’,1e-16,’FunctionTolerance’,1e-16);
lb = [];
ub = [];
[vals, resnorm, out, flag] = lsqcurvefit(Eqn7, coeff0, V, data(:,2),lb,ub);
plot(data(:,1),data(:,2),’x’,data(:,1),Eqn7(vals,V),’b-‘)I am trying to use lsqcurvefit to fit an equation to some data in order to solve for a couple variables. I have included the part of the code below that covers this. I am trying to solve for coeff(1) and coeff(2), The problem is that when I run lsqcurvefit, it is just using whatever my initial guesses are and outputting that as the solution. I suspect it is because my values for the coefficients will be several orders of magnitude different. You can kind of get an idea for this by looking at coeff0. Has anyone else run into this problem and/or do you know how to work around it? Any insight would be greatly appreciated.
load(‘V1.mat’)
load(‘Vp.mat’)
load(‘data.mat’)
V = [V1, Vp]; %voltages
a = 1.1792;
b = 0.5;
e = 1.60217662e-19;
Area = 4.7909e-7;
mi = 39.948./(6.022e23.*1000);
coeff0 = [7e10 4]; %initial guess
Eqn7 = @(coeff, VV) e^1.5*coeff(1)*Area*sqrt(coeff(2)/(2*pi*mi))*100^3*… (a*(-VV(:,1)/coeff(2)).^b.*tanh(VV(:,2)/(2*coeff(2))) + …
(a*(-VV(:,1)/coeff(2)).^b – a*(-(VV(:,1)+VV(:,2))/coeff(2)).^b)./(exp(VV(:,2)/coeff(2))+1);
options = optimoptions(‘lsqcurvefit’,’Algorithm’,’levenberg-marquardt’,’OptimalityTolerance’,1e-16,’FunctionTolerance’,1e-16);
lb = [];
ub = [];
[vals, resnorm, out, flag] = lsqcurvefit(Eqn7, coeff0, V, data(:,2),lb,ub);
plot(data(:,1),data(:,2),’x’,data(:,1),Eqn7(vals,V),’b-‘) I am trying to use lsqcurvefit to fit an equation to some data in order to solve for a couple variables. I have included the part of the code below that covers this. I am trying to solve for coeff(1) and coeff(2), The problem is that when I run lsqcurvefit, it is just using whatever my initial guesses are and outputting that as the solution. I suspect it is because my values for the coefficients will be several orders of magnitude different. You can kind of get an idea for this by looking at coeff0. Has anyone else run into this problem and/or do you know how to work around it? Any insight would be greatly appreciated.
load(‘V1.mat’)
load(‘Vp.mat’)
load(‘data.mat’)
V = [V1, Vp]; %voltages
a = 1.1792;
b = 0.5;
e = 1.60217662e-19;
Area = 4.7909e-7;
mi = 39.948./(6.022e23.*1000);
coeff0 = [7e10 4]; %initial guess
Eqn7 = @(coeff, VV) e^1.5*coeff(1)*Area*sqrt(coeff(2)/(2*pi*mi))*100^3*… (a*(-VV(:,1)/coeff(2)).^b.*tanh(VV(:,2)/(2*coeff(2))) + …
(a*(-VV(:,1)/coeff(2)).^b – a*(-(VV(:,1)+VV(:,2))/coeff(2)).^b)./(exp(VV(:,2)/coeff(2))+1);
options = optimoptions(‘lsqcurvefit’,’Algorithm’,’levenberg-marquardt’,’OptimalityTolerance’,1e-16,’FunctionTolerance’,1e-16);
lb = [];
ub = [];
[vals, resnorm, out, flag] = lsqcurvefit(Eqn7, coeff0, V, data(:,2),lb,ub);
plot(data(:,1),data(:,2),’x’,data(:,1),Eqn7(vals,V),’b-‘) curve fitting MATLAB Answers — New Questions
Unable to draw the given inter-satellite path.
I wrote a Python script and got a path selection at a certain point as [‘Satellite_185’, ‘Satellite_113’, ‘Satellite_162’, ‘Satellite_108’, ‘Satellite_87’, ‘Satellite_68’, ‘Satellite_305’, ‘Satellite_335’, ‘Satellite_384’]. Then I wrote the following MATLAB code, but it gets stuck at the simulation scene step. I suspect it’s because of the time issue, but I can’t fix it.
% Create Satellite Scenario
startTime = datetime(2021,12,10,18,27,57); % 10 December 2021, 6:27:57 PM UTC
stopTime = startTime + hours(3); % 10 December 2021, 9:27:57 PM UTC
sampleTime = 60; % Seconds
sc = satelliteScenario(startTime,stopTime,sampleTime,"AutoSimulate",false);
% Load the entire constellation, but we’ll only use the specified relay satellites
satellites = satellite(sc,"largeConstellation2.tle");
% Known relay satellite names or identifiers (assuming you have them)
% If you only have indices, you’ll need to map them to satellite objects somehow
% Here we assume you have the satellite objects directly
% relaySats = {…}; % This should be filled with the actual satellite objects
% Example: relaySats = {satellites(10), satellites(20), satellites(30)};
% But since you likely have names or other identifiers, you’ll need to find them
% Or, if you have indices into the ‘satellites’ array
relaySatsIndices = [185, 113, 162, 108, 87, 68, 305, 335, 384]; % Example indices
relaySats = satellites(relaySatsIndices);
% Add Ground Stations
gsSource = groundStation(sc,42.3001,-71.3504, "Name","Source Ground Station");
gsTarget = groundStation(sc,17.4351,78.3824, "Name","Target Ground Station");
% Build the path using the known relay satellite sequence
pathNodes = {gsSource, relaySats, gsTarget};
% Visualize Path
sc.AutoSimulate = true;
ac = access(pathNodes{:});
ac.LineColor = "red";
% Determine Intervals When Calculated Path Can Be Used (if needed)
% intvls = accessIntervals(ac); % Uncomment this line if you need the access intervals
% Create satellite scenario viewer
v = satelliteScenarioViewer(sc,"ShowDetails",false);
% Note: Setting MarkerSize directly on the satellites object may not work as expected.
% Instead, adjust the visualization properties in the viewer or use a loop to set markers.
% Play the scenario
play(sc);
The code above references part of the code from this website:https://www.mathworks.com/help/satcom/ug/multihop-path-select-through-sat-constellation.html
This picture is my stuck interface after running in matlab.I wrote a Python script and got a path selection at a certain point as [‘Satellite_185’, ‘Satellite_113’, ‘Satellite_162’, ‘Satellite_108’, ‘Satellite_87’, ‘Satellite_68’, ‘Satellite_305’, ‘Satellite_335’, ‘Satellite_384’]. Then I wrote the following MATLAB code, but it gets stuck at the simulation scene step. I suspect it’s because of the time issue, but I can’t fix it.
% Create Satellite Scenario
startTime = datetime(2021,12,10,18,27,57); % 10 December 2021, 6:27:57 PM UTC
stopTime = startTime + hours(3); % 10 December 2021, 9:27:57 PM UTC
sampleTime = 60; % Seconds
sc = satelliteScenario(startTime,stopTime,sampleTime,"AutoSimulate",false);
% Load the entire constellation, but we’ll only use the specified relay satellites
satellites = satellite(sc,"largeConstellation2.tle");
% Known relay satellite names or identifiers (assuming you have them)
% If you only have indices, you’ll need to map them to satellite objects somehow
% Here we assume you have the satellite objects directly
% relaySats = {…}; % This should be filled with the actual satellite objects
% Example: relaySats = {satellites(10), satellites(20), satellites(30)};
% But since you likely have names or other identifiers, you’ll need to find them
% Or, if you have indices into the ‘satellites’ array
relaySatsIndices = [185, 113, 162, 108, 87, 68, 305, 335, 384]; % Example indices
relaySats = satellites(relaySatsIndices);
% Add Ground Stations
gsSource = groundStation(sc,42.3001,-71.3504, "Name","Source Ground Station");
gsTarget = groundStation(sc,17.4351,78.3824, "Name","Target Ground Station");
% Build the path using the known relay satellite sequence
pathNodes = {gsSource, relaySats, gsTarget};
% Visualize Path
sc.AutoSimulate = true;
ac = access(pathNodes{:});
ac.LineColor = "red";
% Determine Intervals When Calculated Path Can Be Used (if needed)
% intvls = accessIntervals(ac); % Uncomment this line if you need the access intervals
% Create satellite scenario viewer
v = satelliteScenarioViewer(sc,"ShowDetails",false);
% Note: Setting MarkerSize directly on the satellites object may not work as expected.
% Instead, adjust the visualization properties in the viewer or use a loop to set markers.
% Play the scenario
play(sc);
The code above references part of the code from this website:https://www.mathworks.com/help/satcom/ug/multihop-path-select-through-sat-constellation.html
This picture is my stuck interface after running in matlab. I wrote a Python script and got a path selection at a certain point as [‘Satellite_185’, ‘Satellite_113’, ‘Satellite_162’, ‘Satellite_108’, ‘Satellite_87’, ‘Satellite_68’, ‘Satellite_305’, ‘Satellite_335’, ‘Satellite_384’]. Then I wrote the following MATLAB code, but it gets stuck at the simulation scene step. I suspect it’s because of the time issue, but I can’t fix it.
% Create Satellite Scenario
startTime = datetime(2021,12,10,18,27,57); % 10 December 2021, 6:27:57 PM UTC
stopTime = startTime + hours(3); % 10 December 2021, 9:27:57 PM UTC
sampleTime = 60; % Seconds
sc = satelliteScenario(startTime,stopTime,sampleTime,"AutoSimulate",false);
% Load the entire constellation, but we’ll only use the specified relay satellites
satellites = satellite(sc,"largeConstellation2.tle");
% Known relay satellite names or identifiers (assuming you have them)
% If you only have indices, you’ll need to map them to satellite objects somehow
% Here we assume you have the satellite objects directly
% relaySats = {…}; % This should be filled with the actual satellite objects
% Example: relaySats = {satellites(10), satellites(20), satellites(30)};
% But since you likely have names or other identifiers, you’ll need to find them
% Or, if you have indices into the ‘satellites’ array
relaySatsIndices = [185, 113, 162, 108, 87, 68, 305, 335, 384]; % Example indices
relaySats = satellites(relaySatsIndices);
% Add Ground Stations
gsSource = groundStation(sc,42.3001,-71.3504, "Name","Source Ground Station");
gsTarget = groundStation(sc,17.4351,78.3824, "Name","Target Ground Station");
% Build the path using the known relay satellite sequence
pathNodes = {gsSource, relaySats, gsTarget};
% Visualize Path
sc.AutoSimulate = true;
ac = access(pathNodes{:});
ac.LineColor = "red";
% Determine Intervals When Calculated Path Can Be Used (if needed)
% intvls = accessIntervals(ac); % Uncomment this line if you need the access intervals
% Create satellite scenario viewer
v = satelliteScenarioViewer(sc,"ShowDetails",false);
% Note: Setting MarkerSize directly on the satellites object may not work as expected.
% Instead, adjust the visualization properties in the viewer or use a loop to set markers.
% Play the scenario
play(sc);
The code above references part of the code from this website:https://www.mathworks.com/help/satcom/ug/multihop-path-select-through-sat-constellation.html
This picture is my stuck interface after running in matlab. large satellite constellation MATLAB Answers — New Questions
Why can’t I use the “Load Application” button in my deployed SLRT app to switch between MLDATX files to run on my Speedgoat target?
I have an App Designer app to interact with a Simulink Real-Time (SLRT) simulation running on my Speedgoat target. When running the app in MATLAB, I can switch between multiple MLDATX real-time application files to run on my Speedgoat using this dialog:
Then, I deployed this app to a standalone executable using MATLAB Compiler. However, when I try to click the "Load Application" button in the standalone app, either nothing happens (no dialog opens), or the following error occurs when attempting to load the MLDATX file:
Dot indexing into the result of a function call requires parentheses after the function name. The supported syntax is ‘sIrealtime().internal’.
Since R2024a:
Error communicating with target ‘xx.xx.xx.xx’: Specify the real-time application name in the ‘Application’ property of the Load Button component in the instrument panel app.
Then, I tried to implement a manual logic in my app using app.tg.load() that switches between MLDATX files of the same name located in different folders. This works when launching the app from MATLAB, but not when it’s deployed.I have an App Designer app to interact with a Simulink Real-Time (SLRT) simulation running on my Speedgoat target. When running the app in MATLAB, I can switch between multiple MLDATX real-time application files to run on my Speedgoat using this dialog:
Then, I deployed this app to a standalone executable using MATLAB Compiler. However, when I try to click the "Load Application" button in the standalone app, either nothing happens (no dialog opens), or the following error occurs when attempting to load the MLDATX file:
Dot indexing into the result of a function call requires parentheses after the function name. The supported syntax is ‘sIrealtime().internal’.
Since R2024a:
Error communicating with target ‘xx.xx.xx.xx’: Specify the real-time application name in the ‘Application’ property of the Load Button component in the instrument panel app.
Then, I tried to implement a manual logic in my app using app.tg.load() that switches between MLDATX files of the same name located in different folders. This works when launching the app from MATLAB, but not when it’s deployed. I have an App Designer app to interact with a Simulink Real-Time (SLRT) simulation running on my Speedgoat target. When running the app in MATLAB, I can switch between multiple MLDATX real-time application files to run on my Speedgoat using this dialog:
Then, I deployed this app to a standalone executable using MATLAB Compiler. However, when I try to click the "Load Application" button in the standalone app, either nothing happens (no dialog opens), or the following error occurs when attempting to load the MLDATX file:
Dot indexing into the result of a function call requires parentheses after the function name. The supported syntax is ‘sIrealtime().internal’.
Since R2024a:
Error communicating with target ‘xx.xx.xx.xx’: Specify the real-time application name in the ‘Application’ property of the Load Button component in the instrument panel app.
Then, I tried to implement a manual logic in my app using app.tg.load() that switches between MLDATX files of the same name located in different folders. This works when launching the app from MATLAB, but not when it’s deployed. slrt, app, loadbutton, load, application, slrtappgenerator MATLAB Answers — New Questions
How to Sort Matrix Rows from Highest to Lowest
Simplied my problem so it’s easier to solve. Let’s pretend I have MatrixA that has 2 columns, and I want to sort the rows from highest to lowest depending on the value of the cell in the second column. How would I do this?
I also have a VectorB that starts at 10 and would like to add the value of each row in column 2 of the sorted MatrixA. How would I do this? Note this needs to come after MatrixA is sorted from highest to lowest.
Any suggestions matlab wizards out there? Really want to avoid using loops to make the code inefficient.
%Just creating example of the matrix I want to sort you can ignore this
MatrixA = cell(3,2);
MatrixA{1,1} = "D1";
MatrixA{2,1} = "D2";
MatrixA{3,1} = "D3";
MatrixA{1,2} = 5;
MatrixA{2,2} = 15;
MatrixA{3,2} = 10;
% Creating Vector B based on the already defined values for MatrixA which aren’t in order
VectorA = [10 10+MatrixA{1,2} 10+MatrixA{2,2} 10+MatrixA{3,2}];
% How would I sort MatrixA from highest to lowest here and the values of VectorB to be based on the sorted MatrixA?Simplied my problem so it’s easier to solve. Let’s pretend I have MatrixA that has 2 columns, and I want to sort the rows from highest to lowest depending on the value of the cell in the second column. How would I do this?
I also have a VectorB that starts at 10 and would like to add the value of each row in column 2 of the sorted MatrixA. How would I do this? Note this needs to come after MatrixA is sorted from highest to lowest.
Any suggestions matlab wizards out there? Really want to avoid using loops to make the code inefficient.
%Just creating example of the matrix I want to sort you can ignore this
MatrixA = cell(3,2);
MatrixA{1,1} = "D1";
MatrixA{2,1} = "D2";
MatrixA{3,1} = "D3";
MatrixA{1,2} = 5;
MatrixA{2,2} = 15;
MatrixA{3,2} = 10;
% Creating Vector B based on the already defined values for MatrixA which aren’t in order
VectorA = [10 10+MatrixA{1,2} 10+MatrixA{2,2} 10+MatrixA{3,2}];
% How would I sort MatrixA from highest to lowest here and the values of VectorB to be based on the sorted MatrixA? Simplied my problem so it’s easier to solve. Let’s pretend I have MatrixA that has 2 columns, and I want to sort the rows from highest to lowest depending on the value of the cell in the second column. How would I do this?
I also have a VectorB that starts at 10 and would like to add the value of each row in column 2 of the sorted MatrixA. How would I do this? Note this needs to come after MatrixA is sorted from highest to lowest.
Any suggestions matlab wizards out there? Really want to avoid using loops to make the code inefficient.
%Just creating example of the matrix I want to sort you can ignore this
MatrixA = cell(3,2);
MatrixA{1,1} = "D1";
MatrixA{2,1} = "D2";
MatrixA{3,1} = "D3";
MatrixA{1,2} = 5;
MatrixA{2,2} = 15;
MatrixA{3,2} = 10;
% Creating Vector B based on the already defined values for MatrixA which aren’t in order
VectorA = [10 10+MatrixA{1,2} 10+MatrixA{2,2} 10+MatrixA{3,2}];
% How would I sort MatrixA from highest to lowest here and the values of VectorB to be based on the sorted MatrixA? matlab, matlab code, mathematics, matrix array, matrix, matrix manipulation, matrices, array, arrays, cell array, cell arrays, vector, vectors, vectorization, cell, excel, importing excel data, matlab function, matlab coder, struct, script, speed, solve, sort, filter, fsolve MATLAB Answers — New Questions
MATLAB and Simulink crash on Ubuntu 22.04.2
Running MATLAB R2024a on Ubuntu 22.04.2 LTS, and i found MATLAB and Simulink always get "killed" when i run a model.
This is the message i get before "killed" in terminal : (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels
Also when using Budget Analyzer i am not able to change the values or add new blocks. the window seems freezed. or the buttons and my keyboard seem freezed. But on closing the window it simply get closed, and mouse clicks shows response, but unable to work with the app.Running MATLAB R2024a on Ubuntu 22.04.2 LTS, and i found MATLAB and Simulink always get "killed" when i run a model.
This is the message i get before "killed" in terminal : (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels
Also when using Budget Analyzer i am not able to change the values or add new blocks. the window seems freezed. or the buttons and my keyboard seem freezed. But on closing the window it simply get closed, and mouse clicks shows response, but unable to work with the app. Running MATLAB R2024a on Ubuntu 22.04.2 LTS, and i found MATLAB and Simulink always get "killed" when i run a model.
This is the message i get before "killed" in terminal : (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels
Also when using Budget Analyzer i am not able to change the values or add new blocks. the window seems freezed. or the buttons and my keyboard seem freezed. But on closing the window it simply get closed, and mouse clicks shows response, but unable to work with the app. #performance, ubuntu, 22.04, simulink, budget analyzer, crash, opengl MATLAB Answers — New Questions
Calculating Power of Specific Spatial Frequencies of pictures
Hi experts,
I want to calculate the power of the spatial frequency range 20-30 cycles per picture in an picture. I am not sure how I can accomplish this using MATLAB code. FYI. Cycles per picture is a spatial frequency unit, also called cycles per image.
I downloaded following code online and made some modifications. Could you check the code for me and tell me whether I am correct?
% 1. Read the image
img = imread(‘your_image.jpg’);
img_gray = rgb2gray(img); % Convert to grayscale if the image is colored
% 2. Compute the Fourier transform of the image
img_fft = fft2(double(img_gray));
img_fft_shifted = fftshift(img_fft);
% Get the size of the image
[rows, cols] = size(img_gray);
% Compute the frequency coordinates
u = (-rows/2:(rows/2-1)) / rows;
v = (-cols/2:(cols/2-1)) / cols;
[U, V] = meshgrid(u, v);
D = sqrt(U.^2 + V.^2);
% 3. Calculate the power in the 20-30 cycles per image range
freq_low = 20 / rows;
freq_high = 30 / rows;
mask = (D >= freq_low) & (D <= freq_high);
energy = sum(sum(abs(img_fft_shifted .* mask).^2));
% Output the power
fprintf(‘Power in the range 20-30 cycles per image: %fn’, energy);Hi experts,
I want to calculate the power of the spatial frequency range 20-30 cycles per picture in an picture. I am not sure how I can accomplish this using MATLAB code. FYI. Cycles per picture is a spatial frequency unit, also called cycles per image.
I downloaded following code online and made some modifications. Could you check the code for me and tell me whether I am correct?
% 1. Read the image
img = imread(‘your_image.jpg’);
img_gray = rgb2gray(img); % Convert to grayscale if the image is colored
% 2. Compute the Fourier transform of the image
img_fft = fft2(double(img_gray));
img_fft_shifted = fftshift(img_fft);
% Get the size of the image
[rows, cols] = size(img_gray);
% Compute the frequency coordinates
u = (-rows/2:(rows/2-1)) / rows;
v = (-cols/2:(cols/2-1)) / cols;
[U, V] = meshgrid(u, v);
D = sqrt(U.^2 + V.^2);
% 3. Calculate the power in the 20-30 cycles per image range
freq_low = 20 / rows;
freq_high = 30 / rows;
mask = (D >= freq_low) & (D <= freq_high);
energy = sum(sum(abs(img_fft_shifted .* mask).^2));
% Output the power
fprintf(‘Power in the range 20-30 cycles per image: %fn’, energy); Hi experts,
I want to calculate the power of the spatial frequency range 20-30 cycles per picture in an picture. I am not sure how I can accomplish this using MATLAB code. FYI. Cycles per picture is a spatial frequency unit, also called cycles per image.
I downloaded following code online and made some modifications. Could you check the code for me and tell me whether I am correct?
% 1. Read the image
img = imread(‘your_image.jpg’);
img_gray = rgb2gray(img); % Convert to grayscale if the image is colored
% 2. Compute the Fourier transform of the image
img_fft = fft2(double(img_gray));
img_fft_shifted = fftshift(img_fft);
% Get the size of the image
[rows, cols] = size(img_gray);
% Compute the frequency coordinates
u = (-rows/2:(rows/2-1)) / rows;
v = (-cols/2:(cols/2-1)) / cols;
[U, V] = meshgrid(u, v);
D = sqrt(U.^2 + V.^2);
% 3. Calculate the power in the 20-30 cycles per image range
freq_low = 20 / rows;
freq_high = 30 / rows;
mask = (D >= freq_low) & (D <= freq_high);
energy = sum(sum(abs(img_fft_shifted .* mask).^2));
% Output the power
fprintf(‘Power in the range 20-30 cycles per image: %fn’, energy); digital image processing, fft2, fftshift MATLAB Answers — New Questions
Know if Serialport is connected (in App Designer program); ishandle() always true
I open a serial port to my Arduino and it usually works. I’m trying to take care of various errors, for one of which I need to know if the port handle is there and connected or not. In Command window I can tell when ishandle(MyCom) returns a logical answer
ishandle(app.PicoCom)
ans =
0×0 empty logical array
But programatically determining if it’s there, say with
ishandle(app.PicoCom) == false
ans =
0×0 empty logical array
Doesn’t work, it’s always true. How do I ask a false logical array if it’s false and why does this have to be so hard? Does anybody really need an array response to ishandle(app.PicoCom)? if ~ishandle(app.PicoCom) should be enough.
I also tried if ~exist(…) and even isstr(app.PicoCom.Port) but they don’t work when it’s not a handle.
BTW, ishandle() is only described as for graphic objects and figures and the existing answer doesn’t answer my question
https://www.mathworks.com/matlabcentral/answers/13424-why-does-ishandle-0-return-1?s_tid=srchtitleI open a serial port to my Arduino and it usually works. I’m trying to take care of various errors, for one of which I need to know if the port handle is there and connected or not. In Command window I can tell when ishandle(MyCom) returns a logical answer
ishandle(app.PicoCom)
ans =
0×0 empty logical array
But programatically determining if it’s there, say with
ishandle(app.PicoCom) == false
ans =
0×0 empty logical array
Doesn’t work, it’s always true. How do I ask a false logical array if it’s false and why does this have to be so hard? Does anybody really need an array response to ishandle(app.PicoCom)? if ~ishandle(app.PicoCom) should be enough.
I also tried if ~exist(…) and even isstr(app.PicoCom.Port) but they don’t work when it’s not a handle.
BTW, ishandle() is only described as for graphic objects and figures and the existing answer doesn’t answer my question
https://www.mathworks.com/matlabcentral/answers/13424-why-does-ishandle-0-return-1?s_tid=srchtitle I open a serial port to my Arduino and it usually works. I’m trying to take care of various errors, for one of which I need to know if the port handle is there and connected or not. In Command window I can tell when ishandle(MyCom) returns a logical answer
ishandle(app.PicoCom)
ans =
0×0 empty logical array
But programatically determining if it’s there, say with
ishandle(app.PicoCom) == false
ans =
0×0 empty logical array
Doesn’t work, it’s always true. How do I ask a false logical array if it’s false and why does this have to be so hard? Does anybody really need an array response to ishandle(app.PicoCom)? if ~ishandle(app.PicoCom) should be enough.
I also tried if ~exist(…) and even isstr(app.PicoCom.Port) but they don’t work when it’s not a handle.
BTW, ishandle() is only described as for graphic objects and figures and the existing answer doesn’t answer my question
https://www.mathworks.com/matlabcentral/answers/13424-why-does-ishandle-0-return-1?s_tid=srchtitle ishandle is true when its false MATLAB Answers — New Questions
Wireless connection to PI4 Bullseye ad-hoc mode
We have sucessfully programmed our application to run python scripts on a Pi4 when it is connected to our network via the ethernet lan connection.
We need to go to the next phase where the comptuer connects wirelessly to the PI without a network present. Matlab indicated that this was possible when we reviewed the project during the software decision proesses.
We think we need to turn the PI into a server, however we are not finding a resource with a working link that actually accomplishes this task. Any guidance or direction to links that are known to work would be greatly appreciated.
Hardware Pi4B
PI OS – bullseye
Matlab 2024aWe have sucessfully programmed our application to run python scripts on a Pi4 when it is connected to our network via the ethernet lan connection.
We need to go to the next phase where the comptuer connects wirelessly to the PI without a network present. Matlab indicated that this was possible when we reviewed the project during the software decision proesses.
We think we need to turn the PI into a server, however we are not finding a resource with a working link that actually accomplishes this task. Any guidance or direction to links that are known to work would be greatly appreciated.
Hardware Pi4B
PI OS – bullseye
Matlab 2024a We have sucessfully programmed our application to run python scripts on a Pi4 when it is connected to our network via the ethernet lan connection.
We need to go to the next phase where the comptuer connects wirelessly to the PI without a network present. Matlab indicated that this was possible when we reviewed the project during the software decision proesses.
We think we need to turn the PI into a server, however we are not finding a resource with a working link that actually accomplishes this task. Any guidance or direction to links that are known to work would be greatly appreciated.
Hardware Pi4B
PI OS – bullseye
Matlab 2024a ad-hoc, pi4, bullseye MATLAB Answers — New Questions
Using Shortcuts in MATLAB
Hello Everyone , I am a VS Code user and new to MATLAB , I have many extensions in VS Code which makes my work easier and effortless
I feel that MATLAB is missing some of these features. for example , in VS Code, I frequently use Shift + Alt + Down Arrow or Up Arrow to duplicate lines, but I couldn’t find a similar command in the MATLAB documentation.
I also use several commands repetitively. Is there a way to create shortcuts for these commands in MATLAB? Additionally, I’d like to know if it’s possible to customize these shortcuts, as I am accustomed to different keybindings, and MATLAB’s default shortcuts are not quite what I’m used to.
I am using windows , Could someone please assist me with this?Hello Everyone , I am a VS Code user and new to MATLAB , I have many extensions in VS Code which makes my work easier and effortless
I feel that MATLAB is missing some of these features. for example , in VS Code, I frequently use Shift + Alt + Down Arrow or Up Arrow to duplicate lines, but I couldn’t find a similar command in the MATLAB documentation.
I also use several commands repetitively. Is there a way to create shortcuts for these commands in MATLAB? Additionally, I’d like to know if it’s possible to customize these shortcuts, as I am accustomed to different keybindings, and MATLAB’s default shortcuts are not quite what I’m used to.
I am using windows , Could someone please assist me with this? Hello Everyone , I am a VS Code user and new to MATLAB , I have many extensions in VS Code which makes my work easier and effortless
I feel that MATLAB is missing some of these features. for example , in VS Code, I frequently use Shift + Alt + Down Arrow or Up Arrow to duplicate lines, but I couldn’t find a similar command in the MATLAB documentation.
I also use several commands repetitively. Is there a way to create shortcuts for these commands in MATLAB? Additionally, I’d like to know if it’s possible to customize these shortcuts, as I am accustomed to different keybindings, and MATLAB’s default shortcuts are not quite what I’m used to.
I am using windows , Could someone please assist me with this? matlab, shortcuts MATLAB Answers — New Questions
Can Anyone help me to solve this error?Error using * Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise multiplication, use ‘.
here’s the full code
numAntennasTx = 256; % Number of antennasTx
numAntennasRx = 16; % Number of antennasRx
numBits = 10000000; % Number of random bits
ModulationOrder = 16; % 16QAM
snrValues = 0:5:40; % Range of SNR values
%% Generate Random Bits
bits = randi([0 1], numBits, 1);
%% Convolutional Encoding
trellis = poly2trellis(7, [171 133]); % Example trellis
codedBits = convenc(bits, trellis);
%% Modulation
mod_symbols = qammod(codedBits, ModulationOrder, ‘InputType’, ‘bit’, ‘UnitAveragePower’, true);
%% Ensure the number of symbols can be reshaped properly
numSymbols = length(mod_symbols);
paddingSymbols = mod(numAntennasTx – mod(numSymbols, numAntennasTx), numAntennasTx);
mod_symbols_padded = [mod_symbols; zeros(paddingSymbols, 1)];
%% Reshape modulated symbols to fit Tx antennas
mod_symbols_reshaped = reshape(mod_symbols_padded, numAntennasTx, []);
%% Precoding
H = (randn(numAntennasRx, numAntennasTx) + 1i * randn(numAntennasRx, numAntennasTx)) / sqrt(2*numAntennasRx); % Channel matrix
% Regularized Zero Forcing (RZF) Precoding
lambda = 0.01; % Regularization parameter
WRZF = (H’ / (H*H’ + lambda*eye(numAntennasRx)));
% Phased Zero Forcing (PZF) Precoding
angle_H = angle(H);
phase_shift = exp(-1i*angle_H);
H_pzf = H .* phase_shift;
WPZF = (H_pzf’ / (H_pzf*H_pzf’));
%% Apply Precoding
size(WRZF)
size(mod_symbols_reshaped)
precodedBitsRZF = WRZF * mod_symbols_reshaped; % precoding RZF
precodedBitsPZF = WPZF * mod_symbols_reshaped; % precoding PZF
%% Without Precoding
precodedBitsWP = mod_symbols_reshaped; % No precoding
%% OFDM Modulation with Precoding
OfdmSymbolsRZF = ifft(precodedBitsRZF, [], 2); % OFDM modulation with RZF precoding
OfdmSymbolsPZF = ifft(precodedBitsPZF, [], 2); % OFDM modulation with PZF precoding
OfdmSymbolsWP = ifft(precodedBitsWP, [], 2); % OFDM modulation without precoding
%% Channel AWGN
berRZF = zeros(1, length(snrValues)); % Initialize BER results for RZF
berPZF = zeros(1, length(snrValues)); % Initialize BER results for PZF
berWP = zeros(1, length(snrValues)); % Initialize BER results for no precoding
for i = 1:length(snrValues)
snr = snrValues(i);
noiseVar = 1 / (10^(snr/10));
% Transmit through channel (AWGN) for RZF
rxSymbolsRZF = awgn(H * OfdmSymbolsRZF, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsRZF)) + 1i * randn(size(OfdmSymbolsRZF)));
% Transmit through channel (AWGN) for PZF
rxSymbolsPZF = awgn(H * OfdmSymbolsPZF, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsPZF)) + 1i * randn(size(OfdmSymbolsPZF)));
% Transmit through channel (AWGN) without precoding
rxSymbolsWP = awgn(H * OfdmSymbolsWP, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsWP)) + 1i * randn(size(OfdmSymbolsWP)));
%% OFDM Demodulation
% Serial to Parallel Conversion
receivedSymbolsRZFSerial = reshape(rxSymbolsRZF, [], numAntennasRx).’; % Serial to parallel conversion
receivedSymbolsPZFSerial = reshape(rxSymbolsPZF, [], numAntennasRx).’; % Serial to parallel conversion
receivedSymbolsWPSerial = reshape(rxSymbolsWP, [], numAntennasRx).’; % Serial to parallel conversion
% Perform OFDM demodulation for RZF
rxSymbolsIFFTRZF = fft(receivedSymbolsRZFSerial, [], 2); % FFT
% Perform OFDM demodulation for PZF
rxSymbolsIFFTPZF = fft(receivedSymbolsPZFSerial, [], 2); % FFT
% Perform OFDM demodulation for no precoding
rxSymbolsIFFTWP = fft(receivedSymbolsWPSerial, [], 2); % FFT
%% Parallel to Serial Conversion
rxSymbolsDemod_RZF = reshape(rxSymbolsIFFTRZF.’, [], 1); % Parallel to serial conversion
rxSymbolsDemod_PZF = reshape(rxSymbolsIFFTPZF.’, [], 1); % Parallel to serial conversion
rxSymbolsDemod_WP = reshape(rxSymbolsIFFTWP.’, [], 1); % Parallel to serial conversion
% Remove the padded symbols before demodulation
rxSymbolsDemod_RZF = rxSymbolsDemod_RZF(1:end-paddingSymbols);
rxSymbolsDemod_PZF = rxSymbolsDemod_PZF(1:end-paddingSymbols);
rxSymbolsDemod_WP = rxSymbolsDemod_WP(1:end-paddingSymbols);
% QAM demodulation
demodBitsRZF = qamdemod(rxSymbolsDemod_RZF, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
demodBitsPZF = qamdemod(rxSymbolsDemod_PZF, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
demodBitsWP = qamdemod(rxSymbolsDemod_WP, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
% Calculate the Bit Error Rate (BER)
berRZF(i) = sum(demodBitsRZF ~= codedBits(1:end-paddingSymbols)) / numBits;
berPZF(i) = sum(demodBitsPZF ~= codedBits(1:end-paddingSymbols)) / numBits;
berWP(i) = sum(demodBitsWP ~= codedBits(1:end-paddingSymbols)) / numBits;
end
%% Display Results
fprintf(‘Bit Error Rate (RZF Precoding):n’);
disp(berRZF);
fprintf(‘Bit Error Rate (PZF Precoding):n’);
disp(berPZF);
fprintf(‘Bit Error Rate (Without Precoding):n’);
disp(berWP);
%% Plotting the results
figure;
semilogy(snrValues, berRZF, ‘bs-‘, ‘LineWidth’, 2);
hold on;
semilogy(snrValues, berPZF, ‘gs-‘, ‘LineWidth’, 2);
semilogy(snrValues, berWP, ‘rs-‘, ‘LineWidth’, 2);
xlabel(‘SNR (dB)’);
ylabel(‘Bit Error Rate (BER)’);
legend(‘RZF Precoding’, ‘PZF Precoding’, ‘Without Precoding’);
title(‘Massive MIMO 256×16 Antennas with RZF and PZF Precoding’);
grid on;here’s the full code
numAntennasTx = 256; % Number of antennasTx
numAntennasRx = 16; % Number of antennasRx
numBits = 10000000; % Number of random bits
ModulationOrder = 16; % 16QAM
snrValues = 0:5:40; % Range of SNR values
%% Generate Random Bits
bits = randi([0 1], numBits, 1);
%% Convolutional Encoding
trellis = poly2trellis(7, [171 133]); % Example trellis
codedBits = convenc(bits, trellis);
%% Modulation
mod_symbols = qammod(codedBits, ModulationOrder, ‘InputType’, ‘bit’, ‘UnitAveragePower’, true);
%% Ensure the number of symbols can be reshaped properly
numSymbols = length(mod_symbols);
paddingSymbols = mod(numAntennasTx – mod(numSymbols, numAntennasTx), numAntennasTx);
mod_symbols_padded = [mod_symbols; zeros(paddingSymbols, 1)];
%% Reshape modulated symbols to fit Tx antennas
mod_symbols_reshaped = reshape(mod_symbols_padded, numAntennasTx, []);
%% Precoding
H = (randn(numAntennasRx, numAntennasTx) + 1i * randn(numAntennasRx, numAntennasTx)) / sqrt(2*numAntennasRx); % Channel matrix
% Regularized Zero Forcing (RZF) Precoding
lambda = 0.01; % Regularization parameter
WRZF = (H’ / (H*H’ + lambda*eye(numAntennasRx)));
% Phased Zero Forcing (PZF) Precoding
angle_H = angle(H);
phase_shift = exp(-1i*angle_H);
H_pzf = H .* phase_shift;
WPZF = (H_pzf’ / (H_pzf*H_pzf’));
%% Apply Precoding
size(WRZF)
size(mod_symbols_reshaped)
precodedBitsRZF = WRZF * mod_symbols_reshaped; % precoding RZF
precodedBitsPZF = WPZF * mod_symbols_reshaped; % precoding PZF
%% Without Precoding
precodedBitsWP = mod_symbols_reshaped; % No precoding
%% OFDM Modulation with Precoding
OfdmSymbolsRZF = ifft(precodedBitsRZF, [], 2); % OFDM modulation with RZF precoding
OfdmSymbolsPZF = ifft(precodedBitsPZF, [], 2); % OFDM modulation with PZF precoding
OfdmSymbolsWP = ifft(precodedBitsWP, [], 2); % OFDM modulation without precoding
%% Channel AWGN
berRZF = zeros(1, length(snrValues)); % Initialize BER results for RZF
berPZF = zeros(1, length(snrValues)); % Initialize BER results for PZF
berWP = zeros(1, length(snrValues)); % Initialize BER results for no precoding
for i = 1:length(snrValues)
snr = snrValues(i);
noiseVar = 1 / (10^(snr/10));
% Transmit through channel (AWGN) for RZF
rxSymbolsRZF = awgn(H * OfdmSymbolsRZF, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsRZF)) + 1i * randn(size(OfdmSymbolsRZF)));
% Transmit through channel (AWGN) for PZF
rxSymbolsPZF = awgn(H * OfdmSymbolsPZF, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsPZF)) + 1i * randn(size(OfdmSymbolsPZF)));
% Transmit through channel (AWGN) without precoding
rxSymbolsWP = awgn(H * OfdmSymbolsWP, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsWP)) + 1i * randn(size(OfdmSymbolsWP)));
%% OFDM Demodulation
% Serial to Parallel Conversion
receivedSymbolsRZFSerial = reshape(rxSymbolsRZF, [], numAntennasRx).’; % Serial to parallel conversion
receivedSymbolsPZFSerial = reshape(rxSymbolsPZF, [], numAntennasRx).’; % Serial to parallel conversion
receivedSymbolsWPSerial = reshape(rxSymbolsWP, [], numAntennasRx).’; % Serial to parallel conversion
% Perform OFDM demodulation for RZF
rxSymbolsIFFTRZF = fft(receivedSymbolsRZFSerial, [], 2); % FFT
% Perform OFDM demodulation for PZF
rxSymbolsIFFTPZF = fft(receivedSymbolsPZFSerial, [], 2); % FFT
% Perform OFDM demodulation for no precoding
rxSymbolsIFFTWP = fft(receivedSymbolsWPSerial, [], 2); % FFT
%% Parallel to Serial Conversion
rxSymbolsDemod_RZF = reshape(rxSymbolsIFFTRZF.’, [], 1); % Parallel to serial conversion
rxSymbolsDemod_PZF = reshape(rxSymbolsIFFTPZF.’, [], 1); % Parallel to serial conversion
rxSymbolsDemod_WP = reshape(rxSymbolsIFFTWP.’, [], 1); % Parallel to serial conversion
% Remove the padded symbols before demodulation
rxSymbolsDemod_RZF = rxSymbolsDemod_RZF(1:end-paddingSymbols);
rxSymbolsDemod_PZF = rxSymbolsDemod_PZF(1:end-paddingSymbols);
rxSymbolsDemod_WP = rxSymbolsDemod_WP(1:end-paddingSymbols);
% QAM demodulation
demodBitsRZF = qamdemod(rxSymbolsDemod_RZF, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
demodBitsPZF = qamdemod(rxSymbolsDemod_PZF, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
demodBitsWP = qamdemod(rxSymbolsDemod_WP, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
% Calculate the Bit Error Rate (BER)
berRZF(i) = sum(demodBitsRZF ~= codedBits(1:end-paddingSymbols)) / numBits;
berPZF(i) = sum(demodBitsPZF ~= codedBits(1:end-paddingSymbols)) / numBits;
berWP(i) = sum(demodBitsWP ~= codedBits(1:end-paddingSymbols)) / numBits;
end
%% Display Results
fprintf(‘Bit Error Rate (RZF Precoding):n’);
disp(berRZF);
fprintf(‘Bit Error Rate (PZF Precoding):n’);
disp(berPZF);
fprintf(‘Bit Error Rate (Without Precoding):n’);
disp(berWP);
%% Plotting the results
figure;
semilogy(snrValues, berRZF, ‘bs-‘, ‘LineWidth’, 2);
hold on;
semilogy(snrValues, berPZF, ‘gs-‘, ‘LineWidth’, 2);
semilogy(snrValues, berWP, ‘rs-‘, ‘LineWidth’, 2);
xlabel(‘SNR (dB)’);
ylabel(‘Bit Error Rate (BER)’);
legend(‘RZF Precoding’, ‘PZF Precoding’, ‘Without Precoding’);
title(‘Massive MIMO 256×16 Antennas with RZF and PZF Precoding’);
grid on; here’s the full code
numAntennasTx = 256; % Number of antennasTx
numAntennasRx = 16; % Number of antennasRx
numBits = 10000000; % Number of random bits
ModulationOrder = 16; % 16QAM
snrValues = 0:5:40; % Range of SNR values
%% Generate Random Bits
bits = randi([0 1], numBits, 1);
%% Convolutional Encoding
trellis = poly2trellis(7, [171 133]); % Example trellis
codedBits = convenc(bits, trellis);
%% Modulation
mod_symbols = qammod(codedBits, ModulationOrder, ‘InputType’, ‘bit’, ‘UnitAveragePower’, true);
%% Ensure the number of symbols can be reshaped properly
numSymbols = length(mod_symbols);
paddingSymbols = mod(numAntennasTx – mod(numSymbols, numAntennasTx), numAntennasTx);
mod_symbols_padded = [mod_symbols; zeros(paddingSymbols, 1)];
%% Reshape modulated symbols to fit Tx antennas
mod_symbols_reshaped = reshape(mod_symbols_padded, numAntennasTx, []);
%% Precoding
H = (randn(numAntennasRx, numAntennasTx) + 1i * randn(numAntennasRx, numAntennasTx)) / sqrt(2*numAntennasRx); % Channel matrix
% Regularized Zero Forcing (RZF) Precoding
lambda = 0.01; % Regularization parameter
WRZF = (H’ / (H*H’ + lambda*eye(numAntennasRx)));
% Phased Zero Forcing (PZF) Precoding
angle_H = angle(H);
phase_shift = exp(-1i*angle_H);
H_pzf = H .* phase_shift;
WPZF = (H_pzf’ / (H_pzf*H_pzf’));
%% Apply Precoding
size(WRZF)
size(mod_symbols_reshaped)
precodedBitsRZF = WRZF * mod_symbols_reshaped; % precoding RZF
precodedBitsPZF = WPZF * mod_symbols_reshaped; % precoding PZF
%% Without Precoding
precodedBitsWP = mod_symbols_reshaped; % No precoding
%% OFDM Modulation with Precoding
OfdmSymbolsRZF = ifft(precodedBitsRZF, [], 2); % OFDM modulation with RZF precoding
OfdmSymbolsPZF = ifft(precodedBitsPZF, [], 2); % OFDM modulation with PZF precoding
OfdmSymbolsWP = ifft(precodedBitsWP, [], 2); % OFDM modulation without precoding
%% Channel AWGN
berRZF = zeros(1, length(snrValues)); % Initialize BER results for RZF
berPZF = zeros(1, length(snrValues)); % Initialize BER results for PZF
berWP = zeros(1, length(snrValues)); % Initialize BER results for no precoding
for i = 1:length(snrValues)
snr = snrValues(i);
noiseVar = 1 / (10^(snr/10));
% Transmit through channel (AWGN) for RZF
rxSymbolsRZF = awgn(H * OfdmSymbolsRZF, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsRZF)) + 1i * randn(size(OfdmSymbolsRZF)));
% Transmit through channel (AWGN) for PZF
rxSymbolsPZF = awgn(H * OfdmSymbolsPZF, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsPZF)) + 1i * randn(size(OfdmSymbolsPZF)));
% Transmit through channel (AWGN) without precoding
rxSymbolsWP = awgn(H * OfdmSymbolsWP, snr, ‘measured’) + sqrt(noiseVar/2) * (randn(size(OfdmSymbolsWP)) + 1i * randn(size(OfdmSymbolsWP)));
%% OFDM Demodulation
% Serial to Parallel Conversion
receivedSymbolsRZFSerial = reshape(rxSymbolsRZF, [], numAntennasRx).’; % Serial to parallel conversion
receivedSymbolsPZFSerial = reshape(rxSymbolsPZF, [], numAntennasRx).’; % Serial to parallel conversion
receivedSymbolsWPSerial = reshape(rxSymbolsWP, [], numAntennasRx).’; % Serial to parallel conversion
% Perform OFDM demodulation for RZF
rxSymbolsIFFTRZF = fft(receivedSymbolsRZFSerial, [], 2); % FFT
% Perform OFDM demodulation for PZF
rxSymbolsIFFTPZF = fft(receivedSymbolsPZFSerial, [], 2); % FFT
% Perform OFDM demodulation for no precoding
rxSymbolsIFFTWP = fft(receivedSymbolsWPSerial, [], 2); % FFT
%% Parallel to Serial Conversion
rxSymbolsDemod_RZF = reshape(rxSymbolsIFFTRZF.’, [], 1); % Parallel to serial conversion
rxSymbolsDemod_PZF = reshape(rxSymbolsIFFTPZF.’, [], 1); % Parallel to serial conversion
rxSymbolsDemod_WP = reshape(rxSymbolsIFFTWP.’, [], 1); % Parallel to serial conversion
% Remove the padded symbols before demodulation
rxSymbolsDemod_RZF = rxSymbolsDemod_RZF(1:end-paddingSymbols);
rxSymbolsDemod_PZF = rxSymbolsDemod_PZF(1:end-paddingSymbols);
rxSymbolsDemod_WP = rxSymbolsDemod_WP(1:end-paddingSymbols);
% QAM demodulation
demodBitsRZF = qamdemod(rxSymbolsDemod_RZF, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
demodBitsPZF = qamdemod(rxSymbolsDemod_PZF, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
demodBitsWP = qamdemod(rxSymbolsDemod_WP, ModulationOrder, ‘OutputType’, ‘bit’, ‘UnitAveragePower’, true);
% Calculate the Bit Error Rate (BER)
berRZF(i) = sum(demodBitsRZF ~= codedBits(1:end-paddingSymbols)) / numBits;
berPZF(i) = sum(demodBitsPZF ~= codedBits(1:end-paddingSymbols)) / numBits;
berWP(i) = sum(demodBitsWP ~= codedBits(1:end-paddingSymbols)) / numBits;
end
%% Display Results
fprintf(‘Bit Error Rate (RZF Precoding):n’);
disp(berRZF);
fprintf(‘Bit Error Rate (PZF Precoding):n’);
disp(berPZF);
fprintf(‘Bit Error Rate (Without Precoding):n’);
disp(berWP);
%% Plotting the results
figure;
semilogy(snrValues, berRZF, ‘bs-‘, ‘LineWidth’, 2);
hold on;
semilogy(snrValues, berPZF, ‘gs-‘, ‘LineWidth’, 2);
semilogy(snrValues, berWP, ‘rs-‘, ‘LineWidth’, 2);
xlabel(‘SNR (dB)’);
ylabel(‘Bit Error Rate (BER)’);
legend(‘RZF Precoding’, ‘PZF Precoding’, ‘Without Precoding’);
title(‘Massive MIMO 256×16 Antennas with RZF and PZF Precoding’);
grid on; transferred MATLAB Answers — New Questions
Determining gait cycle from heel marker motion capture data
I have motion capture data of participants walking, jogging and running on a treadmill. Participants had a marker on each heel. I need to determine each gait cycle from this data so that I can then calculate breast range of motion, velocity and acceleration for each gait cycle.I have motion capture data of participants walking, jogging and running on a treadmill. Participants had a marker on each heel. I need to determine each gait cycle from this data so that I can then calculate breast range of motion, velocity and acceleration for each gait cycle. I have motion capture data of participants walking, jogging and running on a treadmill. Participants had a marker on each heel. I need to determine each gait cycle from this data so that I can then calculate breast range of motion, velocity and acceleration for each gait cycle. gait cycle determination, motion capture MATLAB Answers — New Questions
How do you use a one parameter (S11), (s1p extension) file to model a direct RF chip input in RF Budget analyzer.
I’m trying to model the TI AFE7906 and have some one port S11 input reflection files provided that describe the input behaviour of the receive ports. How can these files be entered in the RF Budget Analyer (in the "S-Parameters" element) to do this? I realize the app is looking for a two port file for it’s cascade analysis but I need to model the Rx input at the end of the RF chain.I’m trying to model the TI AFE7906 and have some one port S11 input reflection files provided that describe the input behaviour of the receive ports. How can these files be entered in the RF Budget Analyer (in the "S-Parameters" element) to do this? I realize the app is looking for a two port file for it’s cascade analysis but I need to model the Rx input at the end of the RF chain. I’m trying to model the TI AFE7906 and have some one port S11 input reflection files provided that describe the input behaviour of the receive ports. How can these files be entered in the RF Budget Analyer (in the "S-Parameters" element) to do this? I realize the app is looking for a two port file for it’s cascade analysis but I need to model the Rx input at the end of the RF chain. s1p file MATLAB Answers — New Questions
trying to call a function from a function file in a script file
func = afunction; %trying to make the variable func equivalent to "afunciton",
% the function I created in the afunction file but it doesn’t work 🙁
llim = -5;
ulim = -1;
options = optimset(‘Display’,’iter’,’TolX’,10^-7,’Maxiter’,500);
[x] = fzero(@func, [llim ulim],options);
I have a seperate function file called afunction that has the function afunction (which just has like a f(x)= … function in it), but when I try to run this code the error says "Execution of script afunction as a function is not supported:
/Users/my name/Documents/MATLAB/afunction.m" in line 2func = afunction; %trying to make the variable func equivalent to "afunciton",
% the function I created in the afunction file but it doesn’t work 🙁
llim = -5;
ulim = -1;
options = optimset(‘Display’,’iter’,’TolX’,10^-7,’Maxiter’,500);
[x] = fzero(@func, [llim ulim],options);
I have a seperate function file called afunction that has the function afunction (which just has like a f(x)= … function in it), but when I try to run this code the error says "Execution of script afunction as a function is not supported:
/Users/my name/Documents/MATLAB/afunction.m" in line 2 func = afunction; %trying to make the variable func equivalent to "afunciton",
% the function I created in the afunction file but it doesn’t work 🙁
llim = -5;
ulim = -1;
options = optimset(‘Display’,’iter’,’TolX’,10^-7,’Maxiter’,500);
[x] = fzero(@func, [llim ulim],options);
I have a seperate function file called afunction that has the function afunction (which just has like a f(x)= … function in it), but when I try to run this code the error says "Execution of script afunction as a function is not supported:
/Users/my name/Documents/MATLAB/afunction.m" in line 2 function call MATLAB Answers — New Questions
Numerical integration of area
Hi,
I know this must be so easy but I’m confused. I have a section such as this:
I have both variables depth and distance as vectors:
>> whos depth rotx
Name Size Bytes Class Attributes
depth 69×1 552 double
rotx 69×1 552 double
What is the right way to compute the section area?
Thanks!Hi,
I know this must be so easy but I’m confused. I have a section such as this:
I have both variables depth and distance as vectors:
>> whos depth rotx
Name Size Bytes Class Attributes
depth 69×1 552 double
rotx 69×1 552 double
What is the right way to compute the section area?
Thanks! Hi,
I know this must be so easy but I’m confused. I have a section such as this:
I have both variables depth and distance as vectors:
>> whos depth rotx
Name Size Bytes Class Attributes
depth 69×1 552 double
rotx 69×1 552 double
What is the right way to compute the section area?
Thanks! numerical integration MATLAB Answers — New Questions
How to resolve the error ‘The installed MATLAB Runtime is not compatible with the application’ when executing a standalone application?
I get the following error when executing a standalone application that was created with MATLAB Compiler:
The installed MATLAB Runtime is not compatible with the application. Reinstall
the MATLAB Runtime or the application using the application installer
generated using deploytool.I get the following error when executing a standalone application that was created with MATLAB Compiler:
The installed MATLAB Runtime is not compatible with the application. Reinstall
the MATLAB Runtime or the application using the application installer
generated using deploytool. I get the following error when executing a standalone application that was created with MATLAB Compiler:
The installed MATLAB Runtime is not compatible with the application. Reinstall
the MATLAB Runtime or the application using the application installer
generated using deploytool. MATLAB Answers — New Questions
Trying to update submodules of a project with a script.
Hello,
I’m trying to create a script to facilitate team member when they have to update submodules inside a project to a specific tag.
I have no problem for the upadate, but io’m quite stuck to the commit phase.
I try this list of commands:
commit_message = char(strcat("Moved submodule Standard to ", standard_tag, {newline}, "Moved submodule Common to ", common_tag));
git_command = [‘git commit -m ‘ commit_message];
system(git_command);
but, when i try to execute the script, i have this errors:
error: pathspec ‘submodule’ did not match any file(s) known to git
error: pathspec ‘Standard’ did not match any file(s) known to git
error: pathspec ‘to’ did not match any file(s) known to git
error: pathspec ‘2024R2’ did not match any file(s) known to git
I suppose that my issue is related to this:
git_command = ‘git commit -m Moved submodule Standard to 2024R2
Moved submodule Common to 2024R2′
It seems that the system function can’t isolate correctly the "message" for the commit. How can i solve this one.
Thank you in advance.
Best regards.
ClaudioHello,
I’m trying to create a script to facilitate team member when they have to update submodules inside a project to a specific tag.
I have no problem for the upadate, but io’m quite stuck to the commit phase.
I try this list of commands:
commit_message = char(strcat("Moved submodule Standard to ", standard_tag, {newline}, "Moved submodule Common to ", common_tag));
git_command = [‘git commit -m ‘ commit_message];
system(git_command);
but, when i try to execute the script, i have this errors:
error: pathspec ‘submodule’ did not match any file(s) known to git
error: pathspec ‘Standard’ did not match any file(s) known to git
error: pathspec ‘to’ did not match any file(s) known to git
error: pathspec ‘2024R2’ did not match any file(s) known to git
I suppose that my issue is related to this:
git_command = ‘git commit -m Moved submodule Standard to 2024R2
Moved submodule Common to 2024R2′
It seems that the system function can’t isolate correctly the "message" for the commit. How can i solve this one.
Thank you in advance.
Best regards.
Claudio Hello,
I’m trying to create a script to facilitate team member when they have to update submodules inside a project to a specific tag.
I have no problem for the upadate, but io’m quite stuck to the commit phase.
I try this list of commands:
commit_message = char(strcat("Moved submodule Standard to ", standard_tag, {newline}, "Moved submodule Common to ", common_tag));
git_command = [‘git commit -m ‘ commit_message];
system(git_command);
but, when i try to execute the script, i have this errors:
error: pathspec ‘submodule’ did not match any file(s) known to git
error: pathspec ‘Standard’ did not match any file(s) known to git
error: pathspec ‘to’ did not match any file(s) known to git
error: pathspec ‘2024R2’ did not match any file(s) known to git
I suppose that my issue is related to this:
git_command = ‘git commit -m Moved submodule Standard to 2024R2
Moved submodule Common to 2024R2′
It seems that the system function can’t isolate correctly the "message" for the commit. How can i solve this one.
Thank you in advance.
Best regards.
Claudio git, simulink, submodules, script MATLAB Answers — New Questions