Tag Archives: matlab
How can I programmatically create a new MATLAB script and paste string from system clipboard to it in MATLAB R2021b?
I am using MATLAB R2021b, and I have copied some text to my system clipboard. Is there a way that I can programmatically create a new MATLAB script and then paste the text from system clipboard to it?I am using MATLAB R2021b, and I have copied some text to my system clipboard. Is there a way that I can programmatically create a new MATLAB script and then paste the text from system clipboard to it? I am using MATLAB R2021b, and I have copied some text to my system clipboard. Is there a way that I can programmatically create a new MATLAB script and then paste the text from system clipboard to it? clipboard, fopen, fprintf MATLAB Answers — New Questions
Create Class that is both Heterogeneous and a Handle class
2 things.
1) I am looking to create a class that is both a handle class object which allows reference copies of that first object to be distributed / moved which may edit the contents of the first class object AND also be "matlab.mixin.Heterogeneous" which allows there to be an array of objects that differ in their specific class, but are all derived from one root class. In this case that I am looking for all these objects root and derived to also be handel classes.
2) I’m looking for some way to add/remove oject handles from an object’s properties dynamically. I’m not sure how this is normally handeled is Object Oriented Programming, where objects are moved between other objects like people moving form one location to another location.
For example, if I were to simulate people at a obstical course, I would have a class called People, and a root class called Locations for which there are derived classes from, like Swing, Slide, RockWall exe. In this example I want the people object to have a handle to their current location (object), and the different location classes to have a handle to what person is persent, and what location is next in the obstical course after the current one.
Alternativly, if there is maybe a better way of structuring this then I’ve mentioned I would like to know.
classdef Location < matlab.mixin.Heterogeneous %< handle ??????????? NOT SURE HOW MAKE THIS A HANDLE
% "Location" objects are able to change properties of "Person" obj and
% "Location" obj through the handles stored in this classes local properties
properties
locationID (1,1) uint16 {mustBeInteger,mustBePositive} = 1
person (1,1) Person %handle ref, so this class may make changes to it
%next location in the obstical course:
nextLocation (1,1) Location %handle ref, so this class may make changes to it
end
methods
function movePerson(NewLocation,Person)
%find person’s prev location
prevLocation = Person.currentLocation;
%check if new Location’s person is empty
if isempty(NewLocation.person)
%set person’s prev location to empty
clear(prevLocation.person);%????????? NOT SURE HOW TO DO THIS
%Update Location’s person property
NewLocation.person = Person; %copy person handle to location obj
%Update Person’s Location property
Person.currentLocation = NewLocation; %copy location handel to person obj
end
end
end
end
classdef Swing < Location %< handle
methods
function done = sendNextLocation(Location)
if isempty(Location.nextLocation.person) %Swing objects may only accept one person at at a time
Location.AddPerson(Location.nextLocation,Location.person);
Location.RemovePerson(Location);
done = 1;
else
done = 0;
end
end
end
end
classdef Person < handle
properties
ID (1,1) uint16 {mustBeInteger,mustBePositive} = 1
currentLocation (1,1) Location
end
end2 things.
1) I am looking to create a class that is both a handle class object which allows reference copies of that first object to be distributed / moved which may edit the contents of the first class object AND also be "matlab.mixin.Heterogeneous" which allows there to be an array of objects that differ in their specific class, but are all derived from one root class. In this case that I am looking for all these objects root and derived to also be handel classes.
2) I’m looking for some way to add/remove oject handles from an object’s properties dynamically. I’m not sure how this is normally handeled is Object Oriented Programming, where objects are moved between other objects like people moving form one location to another location.
For example, if I were to simulate people at a obstical course, I would have a class called People, and a root class called Locations for which there are derived classes from, like Swing, Slide, RockWall exe. In this example I want the people object to have a handle to their current location (object), and the different location classes to have a handle to what person is persent, and what location is next in the obstical course after the current one.
Alternativly, if there is maybe a better way of structuring this then I’ve mentioned I would like to know.
classdef Location < matlab.mixin.Heterogeneous %< handle ??????????? NOT SURE HOW MAKE THIS A HANDLE
% "Location" objects are able to change properties of "Person" obj and
% "Location" obj through the handles stored in this classes local properties
properties
locationID (1,1) uint16 {mustBeInteger,mustBePositive} = 1
person (1,1) Person %handle ref, so this class may make changes to it
%next location in the obstical course:
nextLocation (1,1) Location %handle ref, so this class may make changes to it
end
methods
function movePerson(NewLocation,Person)
%find person’s prev location
prevLocation = Person.currentLocation;
%check if new Location’s person is empty
if isempty(NewLocation.person)
%set person’s prev location to empty
clear(prevLocation.person);%????????? NOT SURE HOW TO DO THIS
%Update Location’s person property
NewLocation.person = Person; %copy person handle to location obj
%Update Person’s Location property
Person.currentLocation = NewLocation; %copy location handel to person obj
end
end
end
end
classdef Swing < Location %< handle
methods
function done = sendNextLocation(Location)
if isempty(Location.nextLocation.person) %Swing objects may only accept one person at at a time
Location.AddPerson(Location.nextLocation,Location.person);
Location.RemovePerson(Location);
done = 1;
else
done = 0;
end
end
end
end
classdef Person < handle
properties
ID (1,1) uint16 {mustBeInteger,mustBePositive} = 1
currentLocation (1,1) Location
end
end 2 things.
1) I am looking to create a class that is both a handle class object which allows reference copies of that first object to be distributed / moved which may edit the contents of the first class object AND also be "matlab.mixin.Heterogeneous" which allows there to be an array of objects that differ in their specific class, but are all derived from one root class. In this case that I am looking for all these objects root and derived to also be handel classes.
2) I’m looking for some way to add/remove oject handles from an object’s properties dynamically. I’m not sure how this is normally handeled is Object Oriented Programming, where objects are moved between other objects like people moving form one location to another location.
For example, if I were to simulate people at a obstical course, I would have a class called People, and a root class called Locations for which there are derived classes from, like Swing, Slide, RockWall exe. In this example I want the people object to have a handle to their current location (object), and the different location classes to have a handle to what person is persent, and what location is next in the obstical course after the current one.
Alternativly, if there is maybe a better way of structuring this then I’ve mentioned I would like to know.
classdef Location < matlab.mixin.Heterogeneous %< handle ??????????? NOT SURE HOW MAKE THIS A HANDLE
% "Location" objects are able to change properties of "Person" obj and
% "Location" obj through the handles stored in this classes local properties
properties
locationID (1,1) uint16 {mustBeInteger,mustBePositive} = 1
person (1,1) Person %handle ref, so this class may make changes to it
%next location in the obstical course:
nextLocation (1,1) Location %handle ref, so this class may make changes to it
end
methods
function movePerson(NewLocation,Person)
%find person’s prev location
prevLocation = Person.currentLocation;
%check if new Location’s person is empty
if isempty(NewLocation.person)
%set person’s prev location to empty
clear(prevLocation.person);%????????? NOT SURE HOW TO DO THIS
%Update Location’s person property
NewLocation.person = Person; %copy person handle to location obj
%Update Person’s Location property
Person.currentLocation = NewLocation; %copy location handel to person obj
end
end
end
end
classdef Swing < Location %< handle
methods
function done = sendNextLocation(Location)
if isempty(Location.nextLocation.person) %Swing objects may only accept one person at at a time
Location.AddPerson(Location.nextLocation,Location.person);
Location.RemovePerson(Location);
done = 1;
else
done = 0;
end
end
end
end
classdef Person < handle
properties
ID (1,1) uint16 {mustBeInteger,mustBePositive} = 1
currentLocation (1,1) Location
end
end class, handles MATLAB Answers — New Questions
Saving and Restoring Simulation States in an External Application from a Code-Generated Simulink Model with Custom S-Functions
I have a fixed-step Simulink model that includes a referenced model with a custom S-function. This S-function is built with the legacy code tool using a DLL that was compiled from Ada and C code. I plan to autocode this entire Simulink model into a library, which I intend to use in an external non-Matlab real time environment with optional man-in-the-loop inputs. In this external environment, we want to be able to save the simulation’s state at a certain point and then load it back later to continue the simulation repeatably.
We’re in a planning phase and I need to determine whether this is feasible. I’ve looked through some of the documentation and other questions but this use case seems a little out of the ordinary, and it’s not clear to me that the RestoreOperatingPoint etc will work in this case. Will RestoreOperatingPoint work in this scenario, or is there another approach?I have a fixed-step Simulink model that includes a referenced model with a custom S-function. This S-function is built with the legacy code tool using a DLL that was compiled from Ada and C code. I plan to autocode this entire Simulink model into a library, which I intend to use in an external non-Matlab real time environment with optional man-in-the-loop inputs. In this external environment, we want to be able to save the simulation’s state at a certain point and then load it back later to continue the simulation repeatably.
We’re in a planning phase and I need to determine whether this is feasible. I’ve looked through some of the documentation and other questions but this use case seems a little out of the ordinary, and it’s not clear to me that the RestoreOperatingPoint etc will work in this case. Will RestoreOperatingPoint work in this scenario, or is there another approach? I have a fixed-step Simulink model that includes a referenced model with a custom S-function. This S-function is built with the legacy code tool using a DLL that was compiled from Ada and C code. I plan to autocode this entire Simulink model into a library, which I intend to use in an external non-Matlab real time environment with optional man-in-the-loop inputs. In this external environment, we want to be able to save the simulation’s state at a certain point and then load it back later to continue the simulation repeatably.
We’re in a planning phase and I need to determine whether this is feasible. I’ve looked through some of the documentation and other questions but this use case seems a little out of the ordinary, and it’s not clear to me that the RestoreOperatingPoint etc will work in this case. Will RestoreOperatingPoint work in this scenario, or is there another approach? simulink, code generation, s-function, operating point, ada, c++ MATLAB Answers — New Questions
3D Visualization of Items Arrangement
How do I get the 3D visualization of items in the bin from this algorithm?
%
% Copyright (c) 2015, Yarpiz (www.yarpiz.com)
% All rights reserved. Please read the "license.txt" for license terms.
%
% Project Code: YPAP105
% Project Title: Solving Bin Packing Problem using PSO, FA and IWO
% Publisher: Yarpiz (www.yarpiz.com)
%
% Developer: S. Mostapha Kalami Heris (Member of Yarpiz Team)
%
% Contact Info: sm.kalami@gmail.com, info@yarpiz.com
%
clc;
clear;
close all;
%% Problem Definition
model = CreateModel(); % Create Bin Packing Model
CostFunction = @(x) BinPackingCost(x, model); % Objective Function
nVar = 2*model.n-1; % Number of Decision Variables
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = 0; % Lower Bound of Decision Variables
VarMax = 1; % Upper Bound of Decision Variables
%% PSO Parameters
MaxIt=50; % Maximum Number of Iterations
nPop=20; % Population Size (Swarm Size)
% PSO Parameters
w=1; % Inertia Weight
wdamp=0.99; % Inertia Weight Damping Ratio
c1=1.5; % Personal Learning Coefficient
c2=2.0; % Global Learning Coefficient
% If you would like to use Constriction Coefficients for PSO,
% uncomment the following block and comment the above set of parameters.
% % Constriction Coefficients
% phi1=2.05;
% phi2=2.05;
% phi=phi1+phi2;
% chi=2/(phi-2+sqrt(phi^2-4*phi));
% w=chi; % Inertia Weight
% wdamp=1; % Inertia Weight Damping Ratio
% c1=chi*phi1; % Personal Learning Coefficient
% c2=chi*phi2; % Global Learning Coefficient
% Velocity Limits
VelMax=0.1*(VarMax-VarMin);
VelMin=-VelMax;
nParticleMutation = 2; % Number of Mutations Performed on Each Particle
nGlobalBestMutation = 5; % Number of Mutations Performed on Global Best
%% Initialization
empty_particle.Position=[];
empty_particle.Cost=[];
empty_particle.Sol=[];
empty_particle.Velocity=[];
empty_particle.Best.Position=[];
empty_particle.Best.Cost=[];
empty_particle.Best.Sol=[];
particle=repmat(empty_particle,nPop,1);
GlobalBest.Cost=inf;
for i=1:nPop
% Initialize Position
particle(i).Position=unifrnd(VarMin,VarMax,VarSize);
% Initialize Velocity
particle(i).Velocity=zeros(VarSize);
% Evaluation
[particle(i).Cost, particle(i).Sol]=CostFunction(particle(i).Position);
% Update Personal Best
particle(i).Best.Position=particle(i).Position;
particle(i).Best.Cost=particle(i).Cost;
particle(i).Best.Sol=particle(i).Sol;
% Update Global Best
if particle(i).Best.Cost<GlobalBest.Cost
GlobalBest=particle(i).Best;
end
end
BestCost=zeros(MaxIt,1);
%% PSO Main Loop
for it=1:MaxIt
for i=1:nPop
% Update Velocity
particle(i).Velocity = w*particle(i).Velocity …
+c1*rand(VarSize).*(particle(i).Best.Position-particle(i).Position) …
+c2*rand(VarSize).*(GlobalBest.Position-particle(i).Position);
% Apply Velocity Limits
particle(i).Velocity = max(particle(i).Velocity,VelMin);
particle(i).Velocity = min(particle(i).Velocity,VelMax);
% Update Position
particle(i).Position = particle(i).Position + particle(i).Velocity;
% Velocity Mirror Effect
IsOutside=(particle(i).Position<VarMin | particle(i).Position>VarMax);
particle(i).Velocity(IsOutside)=-particle(i).Velocity(IsOutside);
% Apply Position Limits
particle(i).Position = max(particle(i).Position,VarMin);
particle(i).Position = min(particle(i).Position,VarMax);
% Evaluation
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
% Perform Mutation
for j=1:nParticleMutation
NewParticle = particle(i);
NewParticle.Position = Mutate(particle(i).Position);
[NewParticle.Cost, NewParticle.Sol] = CostFunction(NewParticle.Position);
if NewParticle.Cost <= particle(i).Cost
particle(i) = NewParticle;
end
end
% Update Personal Best
if particle(i).Cost<particle(i).Best.Cost
particle(i).Best.Position=particle(i).Position;
particle(i).Best.Cost=particle(i).Cost;
particle(i).Best.Sol=particle(i).Sol;
% Update Global Best
if particle(i).Best.Cost<GlobalBest.Cost
GlobalBest=particle(i).Best;
end
end
end
% Perform Mutation on Global Best
for i=1:nGlobalBestMutation
NewParticle = GlobalBest;
NewParticle.Position = Mutate(GlobalBest.Position);
[NewParticle.Cost, NewParticle.Sol] = CostFunction(NewParticle.Position);
if NewParticle.Cost <= GlobalBest.Cost
GlobalBest = NewParticle;
end
end
BestCost(it)=GlobalBest.Cost;
disp([‘Iteration ‘ num2str(it) ‘: Best Cost = ‘ num2str(BestCost(it))]);
w=w*wdamp;
end
BestSol = GlobalBest;
%% Results
figure;
plot(BestCost,’LineWidth’,2);
xlabel(‘Iteration’);
ylabel(‘Best Cost’);
grid on;
i got this algorithm from https://www.mathworks.com/matlabcentral/fileexchange/53111-bin-packing-problem-using-ga-pso-fa-and-iwoHow do I get the 3D visualization of items in the bin from this algorithm?
%
% Copyright (c) 2015, Yarpiz (www.yarpiz.com)
% All rights reserved. Please read the "license.txt" for license terms.
%
% Project Code: YPAP105
% Project Title: Solving Bin Packing Problem using PSO, FA and IWO
% Publisher: Yarpiz (www.yarpiz.com)
%
% Developer: S. Mostapha Kalami Heris (Member of Yarpiz Team)
%
% Contact Info: sm.kalami@gmail.com, info@yarpiz.com
%
clc;
clear;
close all;
%% Problem Definition
model = CreateModel(); % Create Bin Packing Model
CostFunction = @(x) BinPackingCost(x, model); % Objective Function
nVar = 2*model.n-1; % Number of Decision Variables
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = 0; % Lower Bound of Decision Variables
VarMax = 1; % Upper Bound of Decision Variables
%% PSO Parameters
MaxIt=50; % Maximum Number of Iterations
nPop=20; % Population Size (Swarm Size)
% PSO Parameters
w=1; % Inertia Weight
wdamp=0.99; % Inertia Weight Damping Ratio
c1=1.5; % Personal Learning Coefficient
c2=2.0; % Global Learning Coefficient
% If you would like to use Constriction Coefficients for PSO,
% uncomment the following block and comment the above set of parameters.
% % Constriction Coefficients
% phi1=2.05;
% phi2=2.05;
% phi=phi1+phi2;
% chi=2/(phi-2+sqrt(phi^2-4*phi));
% w=chi; % Inertia Weight
% wdamp=1; % Inertia Weight Damping Ratio
% c1=chi*phi1; % Personal Learning Coefficient
% c2=chi*phi2; % Global Learning Coefficient
% Velocity Limits
VelMax=0.1*(VarMax-VarMin);
VelMin=-VelMax;
nParticleMutation = 2; % Number of Mutations Performed on Each Particle
nGlobalBestMutation = 5; % Number of Mutations Performed on Global Best
%% Initialization
empty_particle.Position=[];
empty_particle.Cost=[];
empty_particle.Sol=[];
empty_particle.Velocity=[];
empty_particle.Best.Position=[];
empty_particle.Best.Cost=[];
empty_particle.Best.Sol=[];
particle=repmat(empty_particle,nPop,1);
GlobalBest.Cost=inf;
for i=1:nPop
% Initialize Position
particle(i).Position=unifrnd(VarMin,VarMax,VarSize);
% Initialize Velocity
particle(i).Velocity=zeros(VarSize);
% Evaluation
[particle(i).Cost, particle(i).Sol]=CostFunction(particle(i).Position);
% Update Personal Best
particle(i).Best.Position=particle(i).Position;
particle(i).Best.Cost=particle(i).Cost;
particle(i).Best.Sol=particle(i).Sol;
% Update Global Best
if particle(i).Best.Cost<GlobalBest.Cost
GlobalBest=particle(i).Best;
end
end
BestCost=zeros(MaxIt,1);
%% PSO Main Loop
for it=1:MaxIt
for i=1:nPop
% Update Velocity
particle(i).Velocity = w*particle(i).Velocity …
+c1*rand(VarSize).*(particle(i).Best.Position-particle(i).Position) …
+c2*rand(VarSize).*(GlobalBest.Position-particle(i).Position);
% Apply Velocity Limits
particle(i).Velocity = max(particle(i).Velocity,VelMin);
particle(i).Velocity = min(particle(i).Velocity,VelMax);
% Update Position
particle(i).Position = particle(i).Position + particle(i).Velocity;
% Velocity Mirror Effect
IsOutside=(particle(i).Position<VarMin | particle(i).Position>VarMax);
particle(i).Velocity(IsOutside)=-particle(i).Velocity(IsOutside);
% Apply Position Limits
particle(i).Position = max(particle(i).Position,VarMin);
particle(i).Position = min(particle(i).Position,VarMax);
% Evaluation
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
% Perform Mutation
for j=1:nParticleMutation
NewParticle = particle(i);
NewParticle.Position = Mutate(particle(i).Position);
[NewParticle.Cost, NewParticle.Sol] = CostFunction(NewParticle.Position);
if NewParticle.Cost <= particle(i).Cost
particle(i) = NewParticle;
end
end
% Update Personal Best
if particle(i).Cost<particle(i).Best.Cost
particle(i).Best.Position=particle(i).Position;
particle(i).Best.Cost=particle(i).Cost;
particle(i).Best.Sol=particle(i).Sol;
% Update Global Best
if particle(i).Best.Cost<GlobalBest.Cost
GlobalBest=particle(i).Best;
end
end
end
% Perform Mutation on Global Best
for i=1:nGlobalBestMutation
NewParticle = GlobalBest;
NewParticle.Position = Mutate(GlobalBest.Position);
[NewParticle.Cost, NewParticle.Sol] = CostFunction(NewParticle.Position);
if NewParticle.Cost <= GlobalBest.Cost
GlobalBest = NewParticle;
end
end
BestCost(it)=GlobalBest.Cost;
disp([‘Iteration ‘ num2str(it) ‘: Best Cost = ‘ num2str(BestCost(it))]);
w=w*wdamp;
end
BestSol = GlobalBest;
%% Results
figure;
plot(BestCost,’LineWidth’,2);
xlabel(‘Iteration’);
ylabel(‘Best Cost’);
grid on;
i got this algorithm from https://www.mathworks.com/matlabcentral/fileexchange/53111-bin-packing-problem-using-ga-pso-fa-and-iwo How do I get the 3D visualization of items in the bin from this algorithm?
%
% Copyright (c) 2015, Yarpiz (www.yarpiz.com)
% All rights reserved. Please read the "license.txt" for license terms.
%
% Project Code: YPAP105
% Project Title: Solving Bin Packing Problem using PSO, FA and IWO
% Publisher: Yarpiz (www.yarpiz.com)
%
% Developer: S. Mostapha Kalami Heris (Member of Yarpiz Team)
%
% Contact Info: sm.kalami@gmail.com, info@yarpiz.com
%
clc;
clear;
close all;
%% Problem Definition
model = CreateModel(); % Create Bin Packing Model
CostFunction = @(x) BinPackingCost(x, model); % Objective Function
nVar = 2*model.n-1; % Number of Decision Variables
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = 0; % Lower Bound of Decision Variables
VarMax = 1; % Upper Bound of Decision Variables
%% PSO Parameters
MaxIt=50; % Maximum Number of Iterations
nPop=20; % Population Size (Swarm Size)
% PSO Parameters
w=1; % Inertia Weight
wdamp=0.99; % Inertia Weight Damping Ratio
c1=1.5; % Personal Learning Coefficient
c2=2.0; % Global Learning Coefficient
% If you would like to use Constriction Coefficients for PSO,
% uncomment the following block and comment the above set of parameters.
% % Constriction Coefficients
% phi1=2.05;
% phi2=2.05;
% phi=phi1+phi2;
% chi=2/(phi-2+sqrt(phi^2-4*phi));
% w=chi; % Inertia Weight
% wdamp=1; % Inertia Weight Damping Ratio
% c1=chi*phi1; % Personal Learning Coefficient
% c2=chi*phi2; % Global Learning Coefficient
% Velocity Limits
VelMax=0.1*(VarMax-VarMin);
VelMin=-VelMax;
nParticleMutation = 2; % Number of Mutations Performed on Each Particle
nGlobalBestMutation = 5; % Number of Mutations Performed on Global Best
%% Initialization
empty_particle.Position=[];
empty_particle.Cost=[];
empty_particle.Sol=[];
empty_particle.Velocity=[];
empty_particle.Best.Position=[];
empty_particle.Best.Cost=[];
empty_particle.Best.Sol=[];
particle=repmat(empty_particle,nPop,1);
GlobalBest.Cost=inf;
for i=1:nPop
% Initialize Position
particle(i).Position=unifrnd(VarMin,VarMax,VarSize);
% Initialize Velocity
particle(i).Velocity=zeros(VarSize);
% Evaluation
[particle(i).Cost, particle(i).Sol]=CostFunction(particle(i).Position);
% Update Personal Best
particle(i).Best.Position=particle(i).Position;
particle(i).Best.Cost=particle(i).Cost;
particle(i).Best.Sol=particle(i).Sol;
% Update Global Best
if particle(i).Best.Cost<GlobalBest.Cost
GlobalBest=particle(i).Best;
end
end
BestCost=zeros(MaxIt,1);
%% PSO Main Loop
for it=1:MaxIt
for i=1:nPop
% Update Velocity
particle(i).Velocity = w*particle(i).Velocity …
+c1*rand(VarSize).*(particle(i).Best.Position-particle(i).Position) …
+c2*rand(VarSize).*(GlobalBest.Position-particle(i).Position);
% Apply Velocity Limits
particle(i).Velocity = max(particle(i).Velocity,VelMin);
particle(i).Velocity = min(particle(i).Velocity,VelMax);
% Update Position
particle(i).Position = particle(i).Position + particle(i).Velocity;
% Velocity Mirror Effect
IsOutside=(particle(i).Position<VarMin | particle(i).Position>VarMax);
particle(i).Velocity(IsOutside)=-particle(i).Velocity(IsOutside);
% Apply Position Limits
particle(i).Position = max(particle(i).Position,VarMin);
particle(i).Position = min(particle(i).Position,VarMax);
% Evaluation
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
% Perform Mutation
for j=1:nParticleMutation
NewParticle = particle(i);
NewParticle.Position = Mutate(particle(i).Position);
[NewParticle.Cost, NewParticle.Sol] = CostFunction(NewParticle.Position);
if NewParticle.Cost <= particle(i).Cost
particle(i) = NewParticle;
end
end
% Update Personal Best
if particle(i).Cost<particle(i).Best.Cost
particle(i).Best.Position=particle(i).Position;
particle(i).Best.Cost=particle(i).Cost;
particle(i).Best.Sol=particle(i).Sol;
% Update Global Best
if particle(i).Best.Cost<GlobalBest.Cost
GlobalBest=particle(i).Best;
end
end
end
% Perform Mutation on Global Best
for i=1:nGlobalBestMutation
NewParticle = GlobalBest;
NewParticle.Position = Mutate(GlobalBest.Position);
[NewParticle.Cost, NewParticle.Sol] = CostFunction(NewParticle.Position);
if NewParticle.Cost <= GlobalBest.Cost
GlobalBest = NewParticle;
end
end
BestCost(it)=GlobalBest.Cost;
disp([‘Iteration ‘ num2str(it) ‘: Best Cost = ‘ num2str(BestCost(it))]);
w=w*wdamp;
end
BestSol = GlobalBest;
%% Results
figure;
plot(BestCost,’LineWidth’,2);
xlabel(‘Iteration’);
ylabel(‘Best Cost’);
grid on;
i got this algorithm from https://www.mathworks.com/matlabcentral/fileexchange/53111-bin-packing-problem-using-ga-pso-fa-and-iwo pso, particle swarm optimization, 3d plots, bin packing, matlab, algorithm MATLAB Answers — New Questions
How to match matrix elements for a condition?
I am working on App Designer. I have a matrix and want to match the elements 3 by 3 with a condition. The condition is that addition of 3 elements must be near at a value.
I already can match them by making the addition from minimum to maximum, but it does not seem to be optimal. So, I want them to be around a value.I am working on App Designer. I have a matrix and want to match the elements 3 by 3 with a condition. The condition is that addition of 3 elements must be near at a value.
I already can match them by making the addition from minimum to maximum, but it does not seem to be optimal. So, I want them to be around a value. I am working on App Designer. I have a matrix and want to match the elements 3 by 3 with a condition. The condition is that addition of 3 elements must be near at a value.
I already can match them by making the addition from minimum to maximum, but it does not seem to be optimal. So, I want them to be around a value. matlab gui, matlab, appdesigner, app designer, data, sort, match MATLAB Answers — New Questions
summation of aij & i, j dependent function in matlab
Hello, I am trying to create a code that can calculate the local resistance coefficient via formula above. the values of ai and aij are defined.
I have created a code using for loops, but getting a really high number.
I have defined example values for Re, f0, and f1 values below. Using the published graph, I should be getting around 1-1.1
ai and bi are values defined.
Please forgive me, it might be that I got matrix algebra incorrect, as I am thinking that might be the suspicion but not sure what I need to change at this point.
Thank you.
%
% initial contraction from flow, formula from diagram 4.10
%
%
%given test values
Re_0=60.46;
f0=1;
f1=2.7225;
%
ind=8;
acoeff=0;
ai=[-25.12458,18.5076,-170.4147,118.1949,-44.42141,9.09524,-.9244027,.03408265];
for i = 1:ind
acoeff=acoeff+ai(i)*log(Re_0)^i;
end
acoeff
bi=[1.07 1.22 2.933;.05 -.51668 .8333; 0 0 0];
iB=3;
jB=3;
count=0;
B_inner=0;
Bcoeff=0;
for i=1:iB
for j=1:jB
B_inner=B_inner+bi(i,j)*((f0/f1)^j);
end
Bcoeff=Bcoeff+B_inner*log(Re_0)^i;
end
Coeff_local=(acoeff*Bcoeff)*(1-f0/f1)Hello, I am trying to create a code that can calculate the local resistance coefficient via formula above. the values of ai and aij are defined.
I have created a code using for loops, but getting a really high number.
I have defined example values for Re, f0, and f1 values below. Using the published graph, I should be getting around 1-1.1
ai and bi are values defined.
Please forgive me, it might be that I got matrix algebra incorrect, as I am thinking that might be the suspicion but not sure what I need to change at this point.
Thank you.
%
% initial contraction from flow, formula from diagram 4.10
%
%
%given test values
Re_0=60.46;
f0=1;
f1=2.7225;
%
ind=8;
acoeff=0;
ai=[-25.12458,18.5076,-170.4147,118.1949,-44.42141,9.09524,-.9244027,.03408265];
for i = 1:ind
acoeff=acoeff+ai(i)*log(Re_0)^i;
end
acoeff
bi=[1.07 1.22 2.933;.05 -.51668 .8333; 0 0 0];
iB=3;
jB=3;
count=0;
B_inner=0;
Bcoeff=0;
for i=1:iB
for j=1:jB
B_inner=B_inner+bi(i,j)*((f0/f1)^j);
end
Bcoeff=Bcoeff+B_inner*log(Re_0)^i;
end
Coeff_local=(acoeff*Bcoeff)*(1-f0/f1) Hello, I am trying to create a code that can calculate the local resistance coefficient via formula above. the values of ai and aij are defined.
I have created a code using for loops, but getting a really high number.
I have defined example values for Re, f0, and f1 values below. Using the published graph, I should be getting around 1-1.1
ai and bi are values defined.
Please forgive me, it might be that I got matrix algebra incorrect, as I am thinking that might be the suspicion but not sure what I need to change at this point.
Thank you.
%
% initial contraction from flow, formula from diagram 4.10
%
%
%given test values
Re_0=60.46;
f0=1;
f1=2.7225;
%
ind=8;
acoeff=0;
ai=[-25.12458,18.5076,-170.4147,118.1949,-44.42141,9.09524,-.9244027,.03408265];
for i = 1:ind
acoeff=acoeff+ai(i)*log(Re_0)^i;
end
acoeff
bi=[1.07 1.22 2.933;.05 -.51668 .8333; 0 0 0];
iB=3;
jB=3;
count=0;
B_inner=0;
Bcoeff=0;
for i=1:iB
for j=1:jB
B_inner=B_inner+bi(i,j)*((f0/f1)^j);
end
Bcoeff=Bcoeff+B_inner*log(Re_0)^i;
end
Coeff_local=(acoeff*Bcoeff)*(1-f0/f1) matrix, index MATLAB Answers — New Questions
How to improve the simulation time in a comprehensive Simulink battery model?
Hello,
In my Simulink model I want to simulate a battery pack with about 5000 individual cells. These should differ slightly from each other, which is why I use the generic battery model from Simscape for each cell (I don’t have the license for Simscape Battery). Now it is not surprising that the simulation time is very high with this number. However, since the blocks are repeated with serial and parallel connection, I tried to improve the simulation time with Scalable Compilation (Referenced Subsystems) according to the following instructions:
https://de.mathworks.com/help/simscape/ug/prepare-your-model-for-scalable-compilation.html
Contrary to expectations, this worsened the simulation time.
Is there another way to simulate such an extensive model in a reasonable time? I would be very grateful for any suggestions.Hello,
In my Simulink model I want to simulate a battery pack with about 5000 individual cells. These should differ slightly from each other, which is why I use the generic battery model from Simscape for each cell (I don’t have the license for Simscape Battery). Now it is not surprising that the simulation time is very high with this number. However, since the blocks are repeated with serial and parallel connection, I tried to improve the simulation time with Scalable Compilation (Referenced Subsystems) according to the following instructions:
https://de.mathworks.com/help/simscape/ug/prepare-your-model-for-scalable-compilation.html
Contrary to expectations, this worsened the simulation time.
Is there another way to simulate such an extensive model in a reasonable time? I would be very grateful for any suggestions. Hello,
In my Simulink model I want to simulate a battery pack with about 5000 individual cells. These should differ slightly from each other, which is why I use the generic battery model from Simscape for each cell (I don’t have the license for Simscape Battery). Now it is not surprising that the simulation time is very high with this number. However, since the blocks are repeated with serial and parallel connection, I tried to improve the simulation time with Scalable Compilation (Referenced Subsystems) according to the following instructions:
https://de.mathworks.com/help/simscape/ug/prepare-your-model-for-scalable-compilation.html
Contrary to expectations, this worsened the simulation time.
Is there another way to simulate such an extensive model in a reasonable time? I would be very grateful for any suggestions. simscape, battery, simulation time, scalable compilation, referenced subsystems MATLAB Answers — New Questions
How to plot from .txt file
How do I plot the 2D and mesh graphs asked for if this is the code I’m using?
%start with a right triangle of length x = 1 and y = 1
%calculate all values (hypotenuse, perimeter, and area)
%for combinations of x = 1:5 and y = 1:5
%Print all of those as a table to a .txt file
%output should look something like this
%{
x y h p a
1 1 1.4 3.41 0.5
1 2 2.24 5.24 1
…..
…..
….. etc
%}
% using the data from the table
% plot a line (2d) graph of the perimeter(x axis) vs area (y axis)
% plot a mesh (3d) graph with x, y (respectively), and h on the ‘z’ axis
x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
plot(myPerim,myArea)
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
endHow do I plot the 2D and mesh graphs asked for if this is the code I’m using?
%start with a right triangle of length x = 1 and y = 1
%calculate all values (hypotenuse, perimeter, and area)
%for combinations of x = 1:5 and y = 1:5
%Print all of those as a table to a .txt file
%output should look something like this
%{
x y h p a
1 1 1.4 3.41 0.5
1 2 2.24 5.24 1
…..
…..
….. etc
%}
% using the data from the table
% plot a line (2d) graph of the perimeter(x axis) vs area (y axis)
% plot a mesh (3d) graph with x, y (respectively), and h on the ‘z’ axis
x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
plot(myPerim,myArea)
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end How do I plot the 2D and mesh graphs asked for if this is the code I’m using?
%start with a right triangle of length x = 1 and y = 1
%calculate all values (hypotenuse, perimeter, and area)
%for combinations of x = 1:5 and y = 1:5
%Print all of those as a table to a .txt file
%output should look something like this
%{
x y h p a
1 1 1.4 3.41 0.5
1 2 2.24 5.24 1
…..
…..
….. etc
%}
% using the data from the table
% plot a line (2d) graph of the perimeter(x axis) vs area (y axis)
% plot a mesh (3d) graph with x, y (respectively), and h on the ‘z’ axis
x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
plot(myPerim,myArea)
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end plots, mesh, graph, text file, matlab MATLAB Answers — New Questions
Common factor
Is there a function to make it find a common factor in an expression with symbolic variables?
For example:
ab+ac–(matlab command)—>a(b+c)
ThanksIs there a function to make it find a common factor in an expression with symbolic variables?
For example:
ab+ac–(matlab command)—>a(b+c)
Thanks Is there a function to make it find a common factor in an expression with symbolic variables?
For example:
ab+ac–(matlab command)—>a(b+c)
Thanks matlab, factor MATLAB Answers — New Questions
How to make a text file from functions
x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
endx = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end matlab MATLAB Answers — New Questions
How to write all cells of structure in excel sheet ?
Hello all,
I have variable which has 1×1 structure, and this structure has many field (it can be reached to 200). each field has has diffrent size of cells as explained in the images.
I want to write the results in excel sheel. like in the uploaded image:
my code is:
writematrix (‘Day’,’Results_Theta.xlsx’,’WriteMode’,’replacefile’,’Sheet’,’Theta’,’Range’,’A1′);
writematrix (‘Theta 1′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’B1′);
writematrix (‘Theta 2′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’C1′);
writematrix (‘Theta 3′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’D1′);
writematrix (‘Theta 4′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’E1′);
writematrix (‘Theta 5′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’F1′);
writematrix (‘Theta 6′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’G1′);
writematrix (‘Theta 7′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’H1′);
So, how can I write the results?Hello all,
I have variable which has 1×1 structure, and this structure has many field (it can be reached to 200). each field has has diffrent size of cells as explained in the images.
I want to write the results in excel sheel. like in the uploaded image:
my code is:
writematrix (‘Day’,’Results_Theta.xlsx’,’WriteMode’,’replacefile’,’Sheet’,’Theta’,’Range’,’A1′);
writematrix (‘Theta 1′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’B1′);
writematrix (‘Theta 2′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’C1′);
writematrix (‘Theta 3′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’D1′);
writematrix (‘Theta 4′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’E1′);
writematrix (‘Theta 5′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’F1′);
writematrix (‘Theta 6′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’G1′);
writematrix (‘Theta 7′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’H1′);
So, how can I write the results? Hello all,
I have variable which has 1×1 structure, and this structure has many field (it can be reached to 200). each field has has diffrent size of cells as explained in the images.
I want to write the results in excel sheel. like in the uploaded image:
my code is:
writematrix (‘Day’,’Results_Theta.xlsx’,’WriteMode’,’replacefile’,’Sheet’,’Theta’,’Range’,’A1′);
writematrix (‘Theta 1′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’B1′);
writematrix (‘Theta 2′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’C1′);
writematrix (‘Theta 3′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’D1′);
writematrix (‘Theta 4′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’E1′);
writematrix (‘Theta 5′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’F1′);
writematrix (‘Theta 6′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’G1′);
writematrix (‘Theta 7′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’H1′);
So, how can I write the results? writematrix MATLAB Answers — New Questions
How to declare constants and vector as argument for once to use it in multiple functions
Dear all;
In my matlab code i have a parent code called "Main SDM". This code call child function "Child WSO" several time and then this child code call its child "single_dd" several time (about 100 times) which in its place call a child function "Ipv_newton" 3000 time!
The problem is that the two last functions are time consuming since it call each time their and constants and vectors
I want to global this constants and vectors or call it for once in Main SDM: ( Im,V, K,q, T, VT_stc) using input argument till the last function!
How it is possible to do it in multi stage (declare variable in main code and than use input argument for first function and continue until last function !)
Is it possible to do so, If not, what is the best way for my code’s performance
function J = single_dd(X)
global V Ie Im
J1=0;
Im=[0.7645 ……………………………….0.212 0.1035 -0.01 -0.123 -0.21];
V=[-0.2057 -0.1291 -0.0588 ………………. 0.5521 0.5633 0.5736 0.5833 0.59];
function x=Ipv_newton(X,v,x0)
k=1.38064852e-23;
q=1.60217646e-19;
T=33+273.15;
Vt_stc=k*T/q;
Main SDM call Child WSO which call single_dd which call Ipv_newtonDear all;
In my matlab code i have a parent code called "Main SDM". This code call child function "Child WSO" several time and then this child code call its child "single_dd" several time (about 100 times) which in its place call a child function "Ipv_newton" 3000 time!
The problem is that the two last functions are time consuming since it call each time their and constants and vectors
I want to global this constants and vectors or call it for once in Main SDM: ( Im,V, K,q, T, VT_stc) using input argument till the last function!
How it is possible to do it in multi stage (declare variable in main code and than use input argument for first function and continue until last function !)
Is it possible to do so, If not, what is the best way for my code’s performance
function J = single_dd(X)
global V Ie Im
J1=0;
Im=[0.7645 ……………………………….0.212 0.1035 -0.01 -0.123 -0.21];
V=[-0.2057 -0.1291 -0.0588 ………………. 0.5521 0.5633 0.5736 0.5833 0.59];
function x=Ipv_newton(X,v,x0)
k=1.38064852e-23;
q=1.60217646e-19;
T=33+273.15;
Vt_stc=k*T/q;
Main SDM call Child WSO which call single_dd which call Ipv_newton Dear all;
In my matlab code i have a parent code called "Main SDM". This code call child function "Child WSO" several time and then this child code call its child "single_dd" several time (about 100 times) which in its place call a child function "Ipv_newton" 3000 time!
The problem is that the two last functions are time consuming since it call each time their and constants and vectors
I want to global this constants and vectors or call it for once in Main SDM: ( Im,V, K,q, T, VT_stc) using input argument till the last function!
How it is possible to do it in multi stage (declare variable in main code and than use input argument for first function and continue until last function !)
Is it possible to do so, If not, what is the best way for my code’s performance
function J = single_dd(X)
global V Ie Im
J1=0;
Im=[0.7645 ……………………………….0.212 0.1035 -0.01 -0.123 -0.21];
V=[-0.2057 -0.1291 -0.0588 ………………. 0.5521 0.5633 0.5736 0.5833 0.59];
function x=Ipv_newton(X,v,x0)
k=1.38064852e-23;
q=1.60217646e-19;
T=33+273.15;
Vt_stc=k*T/q;
Main SDM call Child WSO which call single_dd which call Ipv_newton performance, profiler, function, global variables, input argument, vector MATLAB Answers — New Questions
Simulink to see Fourier
I have a very simple task but am not being successful.
I have a PWM generator in simulike runing at a certain frequency and certain duty cycle.
I want to take the fourier analysis of it and plot it in a scope.
What i expect to see is the DC component of the perioid signal… (i think?)
So if i have a period signal PWM signal with a magnitude of say 5 and duty cycle of .5 i expect to see a DC of 2.5 out on my scope.
How can i acomplish this? I have tried a few different blocks in simulink but im not getting what im expecting.
Perhaps my expecatations are wrong.I have a very simple task but am not being successful.
I have a PWM generator in simulike runing at a certain frequency and certain duty cycle.
I want to take the fourier analysis of it and plot it in a scope.
What i expect to see is the DC component of the perioid signal… (i think?)
So if i have a period signal PWM signal with a magnitude of say 5 and duty cycle of .5 i expect to see a DC of 2.5 out on my scope.
How can i acomplish this? I have tried a few different blocks in simulink but im not getting what im expecting.
Perhaps my expecatations are wrong. I have a very simple task but am not being successful.
I have a PWM generator in simulike runing at a certain frequency and certain duty cycle.
I want to take the fourier analysis of it and plot it in a scope.
What i expect to see is the DC component of the perioid signal… (i think?)
So if i have a period signal PWM signal with a magnitude of say 5 and duty cycle of .5 i expect to see a DC of 2.5 out on my scope.
How can i acomplish this? I have tried a few different blocks in simulink but im not getting what im expecting.
Perhaps my expecatations are wrong. simulink, fourier MATLAB Answers — New Questions
Imgradient3 function: can we used this function for finding chnage in gradient of surface points.
I generated coordinates by converting 3d image to stl. Now I want to give the x coordinates, y coordinates and z coordinates of all the ponts as input in imgradient3 function. Means instead of Gx, Gy and Gz can we put Intx, Inty and Intz in that function. intx isx coordinates of all the genrated points using surface meshing. I am interested in finding the change in gradient of all the points with respect to their neighbours.I generated coordinates by converting 3d image to stl. Now I want to give the x coordinates, y coordinates and z coordinates of all the ponts as input in imgradient3 function. Means instead of Gx, Gy and Gz can we put Intx, Inty and Intz in that function. intx isx coordinates of all the genrated points using surface meshing. I am interested in finding the change in gradient of all the points with respect to their neighbours. I generated coordinates by converting 3d image to stl. Now I want to give the x coordinates, y coordinates and z coordinates of all the ponts as input in imgradient3 function. Means instead of Gx, Gy and Gz can we put Intx, Inty and Intz in that function. intx isx coordinates of all the genrated points using surface meshing. I am interested in finding the change in gradient of all the points with respect to their neighbours. imgradient3, gradient, change in gradient MATLAB Answers — New Questions
Accessing a vector form a matrix
Hi, I am writing a solver scipt where I will have outputed 3 vectors called x1, x2, and x3. I then plan to turn these into a 3 x (some value tbd) vector, meaning x=[x1, x2, x3].
In the main script I need to plot x1, x2 and x3 independently, which brings me to my question. How do I call, for instance, the x1 vector from the ‘x’ matrix so I can plot it please?Hi, I am writing a solver scipt where I will have outputed 3 vectors called x1, x2, and x3. I then plan to turn these into a 3 x (some value tbd) vector, meaning x=[x1, x2, x3].
In the main script I need to plot x1, x2 and x3 independently, which brings me to my question. How do I call, for instance, the x1 vector from the ‘x’ matrix so I can plot it please? Hi, I am writing a solver scipt where I will have outputed 3 vectors called x1, x2, and x3. I then plan to turn these into a 3 x (some value tbd) vector, meaning x=[x1, x2, x3].
In the main script I need to plot x1, x2 and x3 independently, which brings me to my question. How do I call, for instance, the x1 vector from the ‘x’ matrix so I can plot it please? matrix, vector, callback MATLAB Answers — New Questions
Error in AWGN Using Integers or scalar doubles
Need help correcting the following errors:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in awgn (line 157)
y = sig + noise;
Error in Computerassignmentfinal (line 20)
received_low = awgn(lenna_bits, SNR_low,’measured’);
The code attached.
clc;
clear all;
% Load the lenna image
lenna = imread(‘lenna.png’);
% Convert image to grayscale
lenna_gray = rgb2gray(lenna);
% Convert pixel values to bits
lenna_bits = reshape(de2bi(lenna_gray), [], 1);
% BPSK modulation
Eb_No_low = 0; % Low SNR
Eb_No_high = 4; % High SNR
SNR_low = 10^(Eb_No_low/10);
SNR_high = 10^(Eb_No_high/10);
% Transmit and receive at low SNR
received_low = awgn(lenna_bits, SNR_low,’measured’);
% Demodulation
decoded_low = received_low < 0;
% Reshape decoded bits to original image size
decoded_image_low = reshape(decoded_low, size(lenna_gray));
% Plot original and received image at low SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_low); title(‘Received Image (0 dB SNR)’);
% Transmit and receive at high SNR
received_high = awgn(lenna_bits, SNR_high, ‘measured’);
% Demodulation
decoded_high = received_high < 0;
% Reshape decoded bits to original image size
decoded_image_high = reshape(decoded_high, size(lenna_gray));
% Plot original and received image at high SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_high); title(‘Received Image (4 dB SNR)’);
% Linear error detection code
% Example: Hamming (7,4) code
parityMatrix = [1 1 1 0 1 0 0; 1 1 0 1 0 1 0; 1 0 1 1 0 0 1];
generatorMatrix = [eye(4) parityMatrix’];
% Encode the data
encoded_data = mod(lenna_bits * generatorMatrix, 2);
% Add noise
received_data = awgn(encoded_data, Eb_No_low, ‘measured’);
% Syndrome lookup table for error detection
syndrome_table = syndtable(parityMatrix);
% Decoding with error detection
decoded_data = zeros(size(encoded_data));
errors = zeros(size(encoded_data, 1), 1);
for i = 1:size(encoded_data, 1)
syndrome = mod(received_data(i, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(i) = 1;
else
decoded_data(i, 🙂 = received_data(i, :);
end
end
% Count number of retransmission requests at different SNRs
SNRs = [0, 2, 4, 6, 8, 10];
retransmissions = zeros(size(SNRs));
for i = 1:length(SNRs)
SNR = 10^(SNRs(i)/10);
received_data = awgn(encoded_data, SNR, ‘measured’);
errors = zeros(size(encoded_data, 1), 1);
for j = 1:size(encoded_data, 1)
syndrome = mod(received_data(j, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(j) = 1;
retransmissions(i) = retransmissions(i) + 1;
end
end
end
% Plot number of retransmissions against SNR values
figure;
plot(SNRs, retransmissions, ‘-o’);
xlabel(‘SNR (dB)’);
ylabel(‘Number of Retransmissions’);
title(‘Number of Retransmissions vs SNR’);
% Error correction code
% Example: Reed-Solomon code
n = 255;
k = 223;
t = 16;
rs_encoder = comm.RSEncoder(n, k);
rs_decoder = comm.RSDecoder(n, k);
% Encode data
encoded_rs = step(rs_encoder, double(lenna_bits));
% Add noise
received_rs_low = awgn(encoded_rs, Eb_No_low, ‘measured’);
received_rs_high = awgn(encoded_rs, Eb_No_high, ‘measured’);
% Decode received data
decoded_rs_low = step(rs_decoder, received_rs_low);
decoded_rs_high = step(rs_decoder, received_rs_high);
% Reshape decoded bits to original image size
decoded_image_rs_low = reshape(decoded_rs_low, size(lenna_gray));
decoded_image_rs_high = reshape(decoded_rs_high, size(lenna_gray));
% Plot original and received images with error correction
figure;
subplot(1,2,1); imshow(decoded_image_low); title(‘Received Image (0 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_low); title(‘Received Image (0 dB SNR, Error Correction)’);
figure;
subplot(1,2,1); imshow(decoded_image_high); title(‘Received Image (4 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_high); title(‘Received Image (4 dB SNR, Error Correction)’);Need help correcting the following errors:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in awgn (line 157)
y = sig + noise;
Error in Computerassignmentfinal (line 20)
received_low = awgn(lenna_bits, SNR_low,’measured’);
The code attached.
clc;
clear all;
% Load the lenna image
lenna = imread(‘lenna.png’);
% Convert image to grayscale
lenna_gray = rgb2gray(lenna);
% Convert pixel values to bits
lenna_bits = reshape(de2bi(lenna_gray), [], 1);
% BPSK modulation
Eb_No_low = 0; % Low SNR
Eb_No_high = 4; % High SNR
SNR_low = 10^(Eb_No_low/10);
SNR_high = 10^(Eb_No_high/10);
% Transmit and receive at low SNR
received_low = awgn(lenna_bits, SNR_low,’measured’);
% Demodulation
decoded_low = received_low < 0;
% Reshape decoded bits to original image size
decoded_image_low = reshape(decoded_low, size(lenna_gray));
% Plot original and received image at low SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_low); title(‘Received Image (0 dB SNR)’);
% Transmit and receive at high SNR
received_high = awgn(lenna_bits, SNR_high, ‘measured’);
% Demodulation
decoded_high = received_high < 0;
% Reshape decoded bits to original image size
decoded_image_high = reshape(decoded_high, size(lenna_gray));
% Plot original and received image at high SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_high); title(‘Received Image (4 dB SNR)’);
% Linear error detection code
% Example: Hamming (7,4) code
parityMatrix = [1 1 1 0 1 0 0; 1 1 0 1 0 1 0; 1 0 1 1 0 0 1];
generatorMatrix = [eye(4) parityMatrix’];
% Encode the data
encoded_data = mod(lenna_bits * generatorMatrix, 2);
% Add noise
received_data = awgn(encoded_data, Eb_No_low, ‘measured’);
% Syndrome lookup table for error detection
syndrome_table = syndtable(parityMatrix);
% Decoding with error detection
decoded_data = zeros(size(encoded_data));
errors = zeros(size(encoded_data, 1), 1);
for i = 1:size(encoded_data, 1)
syndrome = mod(received_data(i, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(i) = 1;
else
decoded_data(i, 🙂 = received_data(i, :);
end
end
% Count number of retransmission requests at different SNRs
SNRs = [0, 2, 4, 6, 8, 10];
retransmissions = zeros(size(SNRs));
for i = 1:length(SNRs)
SNR = 10^(SNRs(i)/10);
received_data = awgn(encoded_data, SNR, ‘measured’);
errors = zeros(size(encoded_data, 1), 1);
for j = 1:size(encoded_data, 1)
syndrome = mod(received_data(j, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(j) = 1;
retransmissions(i) = retransmissions(i) + 1;
end
end
end
% Plot number of retransmissions against SNR values
figure;
plot(SNRs, retransmissions, ‘-o’);
xlabel(‘SNR (dB)’);
ylabel(‘Number of Retransmissions’);
title(‘Number of Retransmissions vs SNR’);
% Error correction code
% Example: Reed-Solomon code
n = 255;
k = 223;
t = 16;
rs_encoder = comm.RSEncoder(n, k);
rs_decoder = comm.RSDecoder(n, k);
% Encode data
encoded_rs = step(rs_encoder, double(lenna_bits));
% Add noise
received_rs_low = awgn(encoded_rs, Eb_No_low, ‘measured’);
received_rs_high = awgn(encoded_rs, Eb_No_high, ‘measured’);
% Decode received data
decoded_rs_low = step(rs_decoder, received_rs_low);
decoded_rs_high = step(rs_decoder, received_rs_high);
% Reshape decoded bits to original image size
decoded_image_rs_low = reshape(decoded_rs_low, size(lenna_gray));
decoded_image_rs_high = reshape(decoded_rs_high, size(lenna_gray));
% Plot original and received images with error correction
figure;
subplot(1,2,1); imshow(decoded_image_low); title(‘Received Image (0 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_low); title(‘Received Image (0 dB SNR, Error Correction)’);
figure;
subplot(1,2,1); imshow(decoded_image_high); title(‘Received Image (4 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_high); title(‘Received Image (4 dB SNR, Error Correction)’); Need help correcting the following errors:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in awgn (line 157)
y = sig + noise;
Error in Computerassignmentfinal (line 20)
received_low = awgn(lenna_bits, SNR_low,’measured’);
The code attached.
clc;
clear all;
% Load the lenna image
lenna = imread(‘lenna.png’);
% Convert image to grayscale
lenna_gray = rgb2gray(lenna);
% Convert pixel values to bits
lenna_bits = reshape(de2bi(lenna_gray), [], 1);
% BPSK modulation
Eb_No_low = 0; % Low SNR
Eb_No_high = 4; % High SNR
SNR_low = 10^(Eb_No_low/10);
SNR_high = 10^(Eb_No_high/10);
% Transmit and receive at low SNR
received_low = awgn(lenna_bits, SNR_low,’measured’);
% Demodulation
decoded_low = received_low < 0;
% Reshape decoded bits to original image size
decoded_image_low = reshape(decoded_low, size(lenna_gray));
% Plot original and received image at low SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_low); title(‘Received Image (0 dB SNR)’);
% Transmit and receive at high SNR
received_high = awgn(lenna_bits, SNR_high, ‘measured’);
% Demodulation
decoded_high = received_high < 0;
% Reshape decoded bits to original image size
decoded_image_high = reshape(decoded_high, size(lenna_gray));
% Plot original and received image at high SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_high); title(‘Received Image (4 dB SNR)’);
% Linear error detection code
% Example: Hamming (7,4) code
parityMatrix = [1 1 1 0 1 0 0; 1 1 0 1 0 1 0; 1 0 1 1 0 0 1];
generatorMatrix = [eye(4) parityMatrix’];
% Encode the data
encoded_data = mod(lenna_bits * generatorMatrix, 2);
% Add noise
received_data = awgn(encoded_data, Eb_No_low, ‘measured’);
% Syndrome lookup table for error detection
syndrome_table = syndtable(parityMatrix);
% Decoding with error detection
decoded_data = zeros(size(encoded_data));
errors = zeros(size(encoded_data, 1), 1);
for i = 1:size(encoded_data, 1)
syndrome = mod(received_data(i, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(i) = 1;
else
decoded_data(i, 🙂 = received_data(i, :);
end
end
% Count number of retransmission requests at different SNRs
SNRs = [0, 2, 4, 6, 8, 10];
retransmissions = zeros(size(SNRs));
for i = 1:length(SNRs)
SNR = 10^(SNRs(i)/10);
received_data = awgn(encoded_data, SNR, ‘measured’);
errors = zeros(size(encoded_data, 1), 1);
for j = 1:size(encoded_data, 1)
syndrome = mod(received_data(j, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(j) = 1;
retransmissions(i) = retransmissions(i) + 1;
end
end
end
% Plot number of retransmissions against SNR values
figure;
plot(SNRs, retransmissions, ‘-o’);
xlabel(‘SNR (dB)’);
ylabel(‘Number of Retransmissions’);
title(‘Number of Retransmissions vs SNR’);
% Error correction code
% Example: Reed-Solomon code
n = 255;
k = 223;
t = 16;
rs_encoder = comm.RSEncoder(n, k);
rs_decoder = comm.RSDecoder(n, k);
% Encode data
encoded_rs = step(rs_encoder, double(lenna_bits));
% Add noise
received_rs_low = awgn(encoded_rs, Eb_No_low, ‘measured’);
received_rs_high = awgn(encoded_rs, Eb_No_high, ‘measured’);
% Decode received data
decoded_rs_low = step(rs_decoder, received_rs_low);
decoded_rs_high = step(rs_decoder, received_rs_high);
% Reshape decoded bits to original image size
decoded_image_rs_low = reshape(decoded_rs_low, size(lenna_gray));
decoded_image_rs_high = reshape(decoded_rs_high, size(lenna_gray));
% Plot original and received images with error correction
figure;
subplot(1,2,1); imshow(decoded_image_low); title(‘Received Image (0 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_low); title(‘Received Image (0 dB SNR, Error Correction)’);
figure;
subplot(1,2,1); imshow(decoded_image_high); title(‘Received Image (4 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_high); title(‘Received Image (4 dB SNR, Error Correction)’); error corrections MATLAB Answers — New Questions
When I use Turkish characters in comments, they turn into question marks when I reopen the file
When I use Turkish characters in comments in MATLAB, they turn into question marks when I reopen the file. How can I solve this issue?
I also encounter this problem when using a directory with turkish characters.
I’m using MATLAB 2023B, operating system is Windows 10.When I use Turkish characters in comments in MATLAB, they turn into question marks when I reopen the file. How can I solve this issue?
I also encounter this problem when using a directory with turkish characters.
I’m using MATLAB 2023B, operating system is Windows 10. When I use Turkish characters in comments in MATLAB, they turn into question marks when I reopen the file. How can I solve this issue?
I also encounter this problem when using a directory with turkish characters.
I’m using MATLAB 2023B, operating system is Windows 10. language, characters, encoding MATLAB Answers — New Questions
how to solve my problem that i write
I write this code and i wanne output that show me like a sinc function like picture that i attached. the other point is about my l value that i defined it, i wanne some random number between 11e-6 till 13e-6, is it true like this that i define?
tnx.
clc;
clear;
close all;
capital_lambda = 20e-6;
% define sellmier equation to obtain refractive index
lambda_sh=0.775e-6; % SH wavelength
nlithium_sh = 2.1784;
lambda_ff=1.55e-6; % FF wavelength
nlithium_ff = 2.1376;
% parameters
capital_lambda = 20e-6;
k_sh=(2*pi/lambda_sh)*nlithium_sh;
k_ff=(2*pi/lambda_ff)*nlithium_ff;
Delta_kk = k_sh-2*k_ff;
%km=2*pi/capital_lambda;
L = 1; % Length;
sigma_l = 2; % sigma_l = l*sigma_avg
N=L/(capital_lambda/2); % number of domains
l=unifrnd(11e-6,13e-6,[1,1000]); %
for i=l
f=exp(-(pi.^2) .* (sigma_l.^2)/2.*(l.^2));
Delta_k=(k_sh-2*k_ff)-pi./l;
E3= f .* (sinc((Delta_k .* L)/2)).^2 + ((1-f)/N);
end
plot(E3)
%plot(abs(fftshift(fft2(E3))))
xlabel(‘(Delta_k * L)/pi’);
ylabel(‘SHG Effiency’);I write this code and i wanne output that show me like a sinc function like picture that i attached. the other point is about my l value that i defined it, i wanne some random number between 11e-6 till 13e-6, is it true like this that i define?
tnx.
clc;
clear;
close all;
capital_lambda = 20e-6;
% define sellmier equation to obtain refractive index
lambda_sh=0.775e-6; % SH wavelength
nlithium_sh = 2.1784;
lambda_ff=1.55e-6; % FF wavelength
nlithium_ff = 2.1376;
% parameters
capital_lambda = 20e-6;
k_sh=(2*pi/lambda_sh)*nlithium_sh;
k_ff=(2*pi/lambda_ff)*nlithium_ff;
Delta_kk = k_sh-2*k_ff;
%km=2*pi/capital_lambda;
L = 1; % Length;
sigma_l = 2; % sigma_l = l*sigma_avg
N=L/(capital_lambda/2); % number of domains
l=unifrnd(11e-6,13e-6,[1,1000]); %
for i=l
f=exp(-(pi.^2) .* (sigma_l.^2)/2.*(l.^2));
Delta_k=(k_sh-2*k_ff)-pi./l;
E3= f .* (sinc((Delta_k .* L)/2)).^2 + ((1-f)/N);
end
plot(E3)
%plot(abs(fftshift(fft2(E3))))
xlabel(‘(Delta_k * L)/pi’);
ylabel(‘SHG Effiency’); I write this code and i wanne output that show me like a sinc function like picture that i attached. the other point is about my l value that i defined it, i wanne some random number between 11e-6 till 13e-6, is it true like this that i define?
tnx.
clc;
clear;
close all;
capital_lambda = 20e-6;
% define sellmier equation to obtain refractive index
lambda_sh=0.775e-6; % SH wavelength
nlithium_sh = 2.1784;
lambda_ff=1.55e-6; % FF wavelength
nlithium_ff = 2.1376;
% parameters
capital_lambda = 20e-6;
k_sh=(2*pi/lambda_sh)*nlithium_sh;
k_ff=(2*pi/lambda_ff)*nlithium_ff;
Delta_kk = k_sh-2*k_ff;
%km=2*pi/capital_lambda;
L = 1; % Length;
sigma_l = 2; % sigma_l = l*sigma_avg
N=L/(capital_lambda/2); % number of domains
l=unifrnd(11e-6,13e-6,[1,1000]); %
for i=l
f=exp(-(pi.^2) .* (sigma_l.^2)/2.*(l.^2));
Delta_k=(k_sh-2*k_ff)-pi./l;
E3= f .* (sinc((Delta_k .* L)/2)).^2 + ((1-f)/N);
end
plot(E3)
%plot(abs(fftshift(fft2(E3))))
xlabel(‘(Delta_k * L)/pi’);
ylabel(‘SHG Effiency’); sinc function, hann window, rectangle, fft, shg effiency MATLAB Answers — New Questions
Setting Maximum Array Size Threshold in Simulink Model for Embedded C Code Generation
Hi,
I am trying to understand how to set maximum size arrays threshold in case of a Simulink model that needs to use Matlab functions that support variable size arrays.
Is "Maximum stack size (bytes)" the proper parameter to set? I am asking this since I have to generate a C code for my model for an embedded application and I need to be sure to set an upper threshold for all the variables inside my model.Hi,
I am trying to understand how to set maximum size arrays threshold in case of a Simulink model that needs to use Matlab functions that support variable size arrays.
Is "Maximum stack size (bytes)" the proper parameter to set? I am asking this since I have to generate a C code for my model for an embedded application and I need to be sure to set an upper threshold for all the variables inside my model. Hi,
I am trying to understand how to set maximum size arrays threshold in case of a Simulink model that needs to use Matlab functions that support variable size arrays.
Is "Maximum stack size (bytes)" the proper parameter to set? I am asking this since I have to generate a C code for my model for an embedded application and I need to be sure to set an upper threshold for all the variables inside my model. code generation, optimization MATLAB Answers — New Questions
Why is it that Line objects can be instances of two different classes? How can I use findobj to detect only chart primitives?
Using findobj, I have ended up with two arrays of Line graphics handles,
load handleArrays
hL
hD
However, the arrays do not appear to belong to a common class,
whos hL hD
Moreover, even though hD clearly has all the same properties as hL, it cannot be accessed with standard indexing, e.g.,
isprop(hD(1),’Color’)
hD.Color
What is the function of these two different handle graphics types, and how do I tell findobj to retrieve only the hL kind and not the hD kind?Using findobj, I have ended up with two arrays of Line graphics handles,
load handleArrays
hL
hD
However, the arrays do not appear to belong to a common class,
whos hL hD
Moreover, even though hD clearly has all the same properties as hL, it cannot be accessed with standard indexing, e.g.,
isprop(hD(1),’Color’)
hD.Color
What is the function of these two different handle graphics types, and how do I tell findobj to retrieve only the hL kind and not the hD kind? Using findobj, I have ended up with two arrays of Line graphics handles,
load handleArrays
hL
hD
However, the arrays do not appear to belong to a common class,
whos hL hD
Moreover, even though hD clearly has all the same properties as hL, it cannot be accessed with standard indexing, e.g.,
isprop(hD(1),’Color’)
hD.Color
What is the function of these two different handle graphics types, and how do I tell findobj to retrieve only the hL kind and not the hD kind? graphics, line, handles MATLAB Answers — New Questions