Category: Matlab
Category Archives: Matlab
Using Coulomb Counting Method for SoC Estimation of battery
Hi There
I would like to ask if any one could help in turing this into a MATLAB script. Where there Battery voltage and current capacity is asked along with the hours used and then those inputs is used to calculte the state of charge. some thing like what is shown in the picture.
ThanksHi There
I would like to ask if any one could help in turing this into a MATLAB script. Where there Battery voltage and current capacity is asked along with the hours used and then those inputs is used to calculte the state of charge. some thing like what is shown in the picture.
Thanks Hi There
I would like to ask if any one could help in turing this into a MATLAB script. Where there Battery voltage and current capacity is asked along with the hours used and then those inputs is used to calculte the state of charge. some thing like what is shown in the picture.
Thanks battery_system_management MATLAB Answers — New Questions
I need help with an error I get
I have to write a bit of code for an assignment and I keep getting an error and I dont know how to solve it.
I have to determine the position, velocity and acceleration. funcao_forca is a function of a force that is defined in another script. It keeps telling me that F is not recognized. How do I go about this?
function [posicao, velocidade, aceleracao] = atleta(t, f, M)
f = funcao_forca(t,F);
dt = 1;
t1 = [0:dt:t];
aceleracao = zeros(size(t1));
aceleracao = f/M;
velocidade = zeros(size(t1));
for i = 2:length(t1)
velocidade(i) = velocidade(i-1) + aceleracao(i) * (t1(i) – t1(i-1));
end
posicao = zeros(size(t1));
for i = 2:length(t1)
posicao(i) = posicao(i-1) + velocidade(i-1) + 0.5 * aceleracao(i) * (t1(i) – t1(i-1))^2;
end
endI have to write a bit of code for an assignment and I keep getting an error and I dont know how to solve it.
I have to determine the position, velocity and acceleration. funcao_forca is a function of a force that is defined in another script. It keeps telling me that F is not recognized. How do I go about this?
function [posicao, velocidade, aceleracao] = atleta(t, f, M)
f = funcao_forca(t,F);
dt = 1;
t1 = [0:dt:t];
aceleracao = zeros(size(t1));
aceleracao = f/M;
velocidade = zeros(size(t1));
for i = 2:length(t1)
velocidade(i) = velocidade(i-1) + aceleracao(i) * (t1(i) – t1(i-1));
end
posicao = zeros(size(t1));
for i = 2:length(t1)
posicao(i) = posicao(i-1) + velocidade(i-1) + 0.5 * aceleracao(i) * (t1(i) – t1(i-1))^2;
end
end I have to write a bit of code for an assignment and I keep getting an error and I dont know how to solve it.
I have to determine the position, velocity and acceleration. funcao_forca is a function of a force that is defined in another script. It keeps telling me that F is not recognized. How do I go about this?
function [posicao, velocidade, aceleracao] = atleta(t, f, M)
f = funcao_forca(t,F);
dt = 1;
t1 = [0:dt:t];
aceleracao = zeros(size(t1));
aceleracao = f/M;
velocidade = zeros(size(t1));
for i = 2:length(t1)
velocidade(i) = velocidade(i-1) + aceleracao(i) * (t1(i) – t1(i-1));
end
posicao = zeros(size(t1));
for i = 2:length(t1)
posicao(i) = posicao(i-1) + velocidade(i-1) + 0.5 * aceleracao(i) * (t1(i) – t1(i-1))^2;
end
end code, help, error MATLAB Answers — New Questions
When multiplying or dividing a vector by a scaler, when do you need a period before the operator?
This was a question I had, the picture of the problem and the correct answer is attached, thanks.This was a question I had, the picture of the problem and the correct answer is attached, thanks. This was a question I had, the picture of the problem and the correct answer is attached, thanks. vector, scaler, problem MATLAB Answers — New Questions
Examples of Simulink models of spacecraft subsystems controlled by FPGA algorithms
According to the documentation, Matlab/Simulink provides a number of tools for developing spacecraft systems. Among them, keywords such as: Satellite Communications Toolbox, Building Satellite Communication Systems, Satellite Scenario Modeling, SatCom Link Simulation, Model Spacecraft, Satellite Mission Analysis.
According to this link [MATLAB and Simulink for Space Systems], we can also use Matlab and Simulink for "Analyze RF and digital communications subsystems and deploy the algorithms on FPGAs".
I would like to use some of these tools, as well as models of spacecraft subsystems, to debug and simulate FPGA algorithms.
Unfortunately, I did not find examples of such models and tutorials in the documentation and other sources. Can anyone help me with this and suggest some good examples of spacecraft subsystem models controlled by FPGA algorithms?According to the documentation, Matlab/Simulink provides a number of tools for developing spacecraft systems. Among them, keywords such as: Satellite Communications Toolbox, Building Satellite Communication Systems, Satellite Scenario Modeling, SatCom Link Simulation, Model Spacecraft, Satellite Mission Analysis.
According to this link [MATLAB and Simulink for Space Systems], we can also use Matlab and Simulink for "Analyze RF and digital communications subsystems and deploy the algorithms on FPGAs".
I would like to use some of these tools, as well as models of spacecraft subsystems, to debug and simulate FPGA algorithms.
Unfortunately, I did not find examples of such models and tutorials in the documentation and other sources. Can anyone help me with this and suggest some good examples of spacecraft subsystem models controlled by FPGA algorithms? According to the documentation, Matlab/Simulink provides a number of tools for developing spacecraft systems. Among them, keywords such as: Satellite Communications Toolbox, Building Satellite Communication Systems, Satellite Scenario Modeling, SatCom Link Simulation, Model Spacecraft, Satellite Mission Analysis.
According to this link [MATLAB and Simulink for Space Systems], we can also use Matlab and Simulink for "Analyze RF and digital communications subsystems and deploy the algorithms on FPGAs".
I would like to use some of these tools, as well as models of spacecraft subsystems, to debug and simulate FPGA algorithms.
Unfortunately, I did not find examples of such models and tutorials in the documentation and other sources. Can anyone help me with this and suggest some good examples of spacecraft subsystem models controlled by FPGA algorithms? matlab, simulink, spacecraft, fpga, pld, satellite MATLAB Answers — New Questions
Problem to connect external webcam on raspberry pi
When trying to connect the raspi camera in matlab I get the following error: Seed must be a double scalar.When trying to connect the raspi camera in matlab I get the following error: Seed must be a double scalar. When trying to connect the raspi camera in matlab I get the following error: Seed must be a double scalar. raspberry pi, camera MATLAB Answers — New Questions
how to convert logical array in arraycell
logical2cellstr not working..there is a similar words reserved?logical2cellstr not working..there is a similar words reserved? logical2cellstr not working..there is a similar words reserved? how to convert logical array in arraycell MATLAB Answers — New Questions
how to use local parameter in HDL Coder toolbox?
Dear MATLAB Support Team,
I am currently working on developing an UART transmitter block in Simulink. Within this block, I require two parameters: CLOCK_FREQ and BAUD_RATE, which are essential for calculating the DIVIDER parameter, given by CLOCK_FREQ / BAUD_RATE.
While I have learned how to generate parameters using HDL Coder, I am facing confusion regarding the generation of the local parameter DIVIDER, which will be utilized within a counter block. I aim to produce Verilog code similar to the following:
– – – – – – – –
parameter BAUD_RATE = 9600;
parameter CLOCK_FREQ = 100000000;
localparam DIVIDER = CLOCK_FREQ / BAUD_RATE;
if (clk_divider == DIVIDER) begin
// Further implementation
end
– – – – – – – – –
However, the generated code I am obtaining differs:
– – – – – – – – – – – –
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ = 100000000;
assign DIVIDER_out1 = 32’b00000000000000000010100010110001;
– – – – – – – – – – –
How can I use BAUD_RATE and CLOCK_FREQ within the module to generate other parameters?
The Constant Block setting is as follows:Dear MATLAB Support Team,
I am currently working on developing an UART transmitter block in Simulink. Within this block, I require two parameters: CLOCK_FREQ and BAUD_RATE, which are essential for calculating the DIVIDER parameter, given by CLOCK_FREQ / BAUD_RATE.
While I have learned how to generate parameters using HDL Coder, I am facing confusion regarding the generation of the local parameter DIVIDER, which will be utilized within a counter block. I aim to produce Verilog code similar to the following:
– – – – – – – –
parameter BAUD_RATE = 9600;
parameter CLOCK_FREQ = 100000000;
localparam DIVIDER = CLOCK_FREQ / BAUD_RATE;
if (clk_divider == DIVIDER) begin
// Further implementation
end
– – – – – – – – –
However, the generated code I am obtaining differs:
– – – – – – – – – – – –
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ = 100000000;
assign DIVIDER_out1 = 32’b00000000000000000010100010110001;
– – – – – – – – – – –
How can I use BAUD_RATE and CLOCK_FREQ within the module to generate other parameters?
The Constant Block setting is as follows: Dear MATLAB Support Team,
I am currently working on developing an UART transmitter block in Simulink. Within this block, I require two parameters: CLOCK_FREQ and BAUD_RATE, which are essential for calculating the DIVIDER parameter, given by CLOCK_FREQ / BAUD_RATE.
While I have learned how to generate parameters using HDL Coder, I am facing confusion regarding the generation of the local parameter DIVIDER, which will be utilized within a counter block. I aim to produce Verilog code similar to the following:
– – – – – – – –
parameter BAUD_RATE = 9600;
parameter CLOCK_FREQ = 100000000;
localparam DIVIDER = CLOCK_FREQ / BAUD_RATE;
if (clk_divider == DIVIDER) begin
// Further implementation
end
– – – – – – – – –
However, the generated code I am obtaining differs:
– – – – – – – – – – – –
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ = 100000000;
assign DIVIDER_out1 = 32’b00000000000000000010100010110001;
– – – – – – – – – – –
How can I use BAUD_RATE and CLOCK_FREQ within the module to generate other parameters?
The Constant Block setting is as follows: hdl coder, simulink, verilog MATLAB Answers — New Questions
Creating MP4 with Audio
Hello
I want to create an MP4 file which contains audio. VideoWriter is not suitable, as it doesn’t input any audio data. So, I used _vision.VideoFileWriter_ and _step_. But I have some problems.
When running the code below:
videoFWriter = vision.VideoFileWriter(‘Test.mp4’, ‘FileFormat’, ‘MPEG4’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
I receive the following warning message:
Warning: The AudioInputPort property is not relevant in this configuration of the System object.
When I change the code to the following, the video format is uncompressed AVI, which leads to huge file sizes.
videoFWriter = vision.VideoFileWriter(‘Test.avi’, ‘FileFormat’, ‘AVI’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
step(videoFWriter, FrameScreen, FrameAudio);
_FrameAudio_ contains audio data corresponding to one video frame. It seems that it ignores ‘MJPEG Compressor’.
I would love to be able to directly create .mp4 files, but if not possible, it is fine with me to create good quality compressed .avi files, and use a 3rd party software to convert to .mp4. I would appreciate any suggestions. Thanks.
My OS is Windows 7, and MATLAB r2017b.
Cheers
Amir-HomayounHello
I want to create an MP4 file which contains audio. VideoWriter is not suitable, as it doesn’t input any audio data. So, I used _vision.VideoFileWriter_ and _step_. But I have some problems.
When running the code below:
videoFWriter = vision.VideoFileWriter(‘Test.mp4’, ‘FileFormat’, ‘MPEG4’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
I receive the following warning message:
Warning: The AudioInputPort property is not relevant in this configuration of the System object.
When I change the code to the following, the video format is uncompressed AVI, which leads to huge file sizes.
videoFWriter = vision.VideoFileWriter(‘Test.avi’, ‘FileFormat’, ‘AVI’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
step(videoFWriter, FrameScreen, FrameAudio);
_FrameAudio_ contains audio data corresponding to one video frame. It seems that it ignores ‘MJPEG Compressor’.
I would love to be able to directly create .mp4 files, but if not possible, it is fine with me to create good quality compressed .avi files, and use a 3rd party software to convert to .mp4. I would appreciate any suggestions. Thanks.
My OS is Windows 7, and MATLAB r2017b.
Cheers
Amir-Homayoun Hello
I want to create an MP4 file which contains audio. VideoWriter is not suitable, as it doesn’t input any audio data. So, I used _vision.VideoFileWriter_ and _step_. But I have some problems.
When running the code below:
videoFWriter = vision.VideoFileWriter(‘Test.mp4’, ‘FileFormat’, ‘MPEG4’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
I receive the following warning message:
Warning: The AudioInputPort property is not relevant in this configuration of the System object.
When I change the code to the following, the video format is uncompressed AVI, which leads to huge file sizes.
videoFWriter = vision.VideoFileWriter(‘Test.avi’, ‘FileFormat’, ‘AVI’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
step(videoFWriter, FrameScreen, FrameAudio);
_FrameAudio_ contains audio data corresponding to one video frame. It seems that it ignores ‘MJPEG Compressor’.
I would love to be able to directly create .mp4 files, but if not possible, it is fine with me to create good quality compressed .avi files, and use a 3rd party software to convert to .mp4. I would appreciate any suggestions. Thanks.
My OS is Windows 7, and MATLAB r2017b.
Cheers
Amir-Homayoun mp4, audio, compression, video, avi, movie, mpeg4, videofilewriter, videowriter, sound MATLAB Answers — New Questions
roadrunner logic editor PID control
In the Roadrunner logic editor, is there a way to control PID using parameter values already obtained through optimization?In the Roadrunner logic editor, is there a way to control PID using parameter values already obtained through optimization? In the Roadrunner logic editor, is there a way to control PID using parameter values already obtained through optimization? roadrunner, logiceditor MATLAB Answers — New Questions
normpdf is taking zeros
Hello, I am using the normpdf command to evaluate a function in MATLAB. When the argument of normpdf is too small, MATLAB reports a zero. Is is possible to get the exact value of normpdf instead of 0?Hello, I am using the normpdf command to evaluate a function in MATLAB. When the argument of normpdf is too small, MATLAB reports a zero. Is is possible to get the exact value of normpdf instead of 0? Hello, I am using the normpdf command to evaluate a function in MATLAB. When the argument of normpdf is too small, MATLAB reports a zero. Is is possible to get the exact value of normpdf instead of 0? normpdf MATLAB Answers — New Questions
how to solve the error comes in line 25
clear, clc
format longg
GM = 0.3986004415E+15;
alpha = 0.63781363E+07;
% Load data
%data = importdata(‘EGM08.txt’);
data = readtable(‘EGM08.txt’, ‘ReadVariableNames’, false);
% Extract sigma and beta values
sigma = data(:,5);
beta = data(:,6);
% Initialize Dw
Dw = 0;
% Calculate Dw using the equation
for n = 0:78
summation = 0;
for m = 0:2190
summation = summation + (sigma(m+1)^2 + beta(m+1)^2); % This is the line 25
end
Dw = Dw + sqrt((GM/alpha)^2 * summation);
end
% Display the result
disp([‘Dw = ‘,num2str(Dw)]);
when running the program the following error comes.
Error using egm2008 (line 25)
Subscripting into a table using one
subscript (as in t(i)) is not
supported. Specify a row subscript and
a variable subscript, as in
t(rows,vars). To select variables, use
t(:,i) or for one variable t.(i). To
select rows, use t(i,:).
EGM08.txt have 2401334 rows and 6 columns.clear, clc
format longg
GM = 0.3986004415E+15;
alpha = 0.63781363E+07;
% Load data
%data = importdata(‘EGM08.txt’);
data = readtable(‘EGM08.txt’, ‘ReadVariableNames’, false);
% Extract sigma and beta values
sigma = data(:,5);
beta = data(:,6);
% Initialize Dw
Dw = 0;
% Calculate Dw using the equation
for n = 0:78
summation = 0;
for m = 0:2190
summation = summation + (sigma(m+1)^2 + beta(m+1)^2); % This is the line 25
end
Dw = Dw + sqrt((GM/alpha)^2 * summation);
end
% Display the result
disp([‘Dw = ‘,num2str(Dw)]);
when running the program the following error comes.
Error using egm2008 (line 25)
Subscripting into a table using one
subscript (as in t(i)) is not
supported. Specify a row subscript and
a variable subscript, as in
t(rows,vars). To select variables, use
t(:,i) or for one variable t.(i). To
select rows, use t(i,:).
EGM08.txt have 2401334 rows and 6 columns. clear, clc
format longg
GM = 0.3986004415E+15;
alpha = 0.63781363E+07;
% Load data
%data = importdata(‘EGM08.txt’);
data = readtable(‘EGM08.txt’, ‘ReadVariableNames’, false);
% Extract sigma and beta values
sigma = data(:,5);
beta = data(:,6);
% Initialize Dw
Dw = 0;
% Calculate Dw using the equation
for n = 0:78
summation = 0;
for m = 0:2190
summation = summation + (sigma(m+1)^2 + beta(m+1)^2); % This is the line 25
end
Dw = Dw + sqrt((GM/alpha)^2 * summation);
end
% Display the result
disp([‘Dw = ‘,num2str(Dw)]);
when running the program the following error comes.
Error using egm2008 (line 25)
Subscripting into a table using one
subscript (as in t(i)) is not
supported. Specify a row subscript and
a variable subscript, as in
t(rows,vars). To select variables, use
t(:,i) or for one variable t.(i). To
select rows, use t(i,:).
EGM08.txt have 2401334 rows and 6 columns. error MATLAB Answers — New Questions
What could be the solution of this error (Parse error ar'(‘:usage might be invalid MATLAB syntax)?
I have the following error that is appearing in my work in %time domain
%time domain
1-tmin=0;
2-tmax=200;
3-dt1= ((2*D)/(U^2))-(deltax/U);
4-deltat=0.8*min([0.1,dt1]);
5-if deltat<0.01
6-deltat=0.01;
end
Line 6 deltat = 0.01;
the error is (Parse error ar'(‘:usage might be invalid MATLAB syntax).I have the following error that is appearing in my work in %time domain
%time domain
1-tmin=0;
2-tmax=200;
3-dt1= ((2*D)/(U^2))-(deltax/U);
4-deltat=0.8*min([0.1,dt1]);
5-if deltat<0.01
6-deltat=0.01;
end
Line 6 deltat = 0.01;
the error is (Parse error ar'(‘:usage might be invalid MATLAB syntax). I have the following error that is appearing in my work in %time domain
%time domain
1-tmin=0;
2-tmax=200;
3-dt1= ((2*D)/(U^2))-(deltax/U);
4-deltat=0.8*min([0.1,dt1]);
5-if deltat<0.01
6-deltat=0.01;
end
Line 6 deltat = 0.01;
the error is (Parse error ar'(‘:usage might be invalid MATLAB syntax). parse error, matlab syntax MATLAB Answers — New Questions
Do MBPO agents not support recurrent neural networks for the environment model, the base off-policy agent, or both?
Since TD3, SAC, etc. agents support using recurrent layers by themselves, would using these recurrent base agents still not work with MBPO?
Could this limit be circumvented by using a custom training loop for the environment model and for the base agents?Since TD3, SAC, etc. agents support using recurrent layers by themselves, would using these recurrent base agents still not work with MBPO?
Could this limit be circumvented by using a custom training loop for the environment model and for the base agents? Since TD3, SAC, etc. agents support using recurrent layers by themselves, would using these recurrent base agents still not work with MBPO?
Could this limit be circumvented by using a custom training loop for the environment model and for the base agents? mbpo MATLAB Answers — New Questions
How do you combine multiple sliders into one on Matlab?
I have 3 different sliders doing 3 different things and I’m trying to have all the things being done to it in one function at the same time. I’ve tried many different things and I still don’t know how. If anybody could provide some insight that would be greatly appreciated.
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
conslider = uislider;
conslider.Position = [150 20 300 3];
conslider.Limits = [0 2];
conslider.Value = 1;
conslider.MajorTicks = [0 0.5 1 1.5 2];
conslider.ValueChangedFcn = @updateImage;
function updateImage(conslider,~)
contrastFactor = conslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imadjust(outputImage, [], [], contrastFactor);
% Display the updated image
imshow(outputImage);
title([‘contrastFactor: ‘ num2str(contrastFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
% Developing a slider to adjust the saturation
satslider = uislider;
satslider.Position = [150 20 300 3];
satslider.Limits = [0 2];
satslider.Value = 1;
satslider.MajorTicks = [0 0.5 1 1.5 2];
satslider.ValueChangedFcn = @updateImage
function updateImage(satslider,~)
% Read the current saturation value from the slider
saturationFactor = satslider.Value;
% Convert the image to HSV color space
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
% Update the saturation (S)
hsvImage(:, :, 2) = hsvImage(:, :, 2) * saturationFactor;
% Convert the modified image back to RGB color space
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
% Display the updated image
imshow(outputImage);
title([‘Saturation Factor: ‘ num2str(saturationFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
sharpslider = uislider;
sharpslider.Position = [150 20 300 3];
sharpslider.Limits = [0 2];
sharpslider.Value = 1;
sharpslider.MajorTicks = [0 0.5 1 1.5 2];
sharpslider.ValueChangedFcn = @updateImage;
function updateImage(sharpslider,~)
sharpenFactor = sharpslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imsharpen(inputImage, ‘Amount’, sharpenFactor);
% Display the updated image
imshow(outputImage);
title([‘sharpenFactor: ‘ num2str(sharpenFactor)]);
endI have 3 different sliders doing 3 different things and I’m trying to have all the things being done to it in one function at the same time. I’ve tried many different things and I still don’t know how. If anybody could provide some insight that would be greatly appreciated.
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
conslider = uislider;
conslider.Position = [150 20 300 3];
conslider.Limits = [0 2];
conslider.Value = 1;
conslider.MajorTicks = [0 0.5 1 1.5 2];
conslider.ValueChangedFcn = @updateImage;
function updateImage(conslider,~)
contrastFactor = conslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imadjust(outputImage, [], [], contrastFactor);
% Display the updated image
imshow(outputImage);
title([‘contrastFactor: ‘ num2str(contrastFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
% Developing a slider to adjust the saturation
satslider = uislider;
satslider.Position = [150 20 300 3];
satslider.Limits = [0 2];
satslider.Value = 1;
satslider.MajorTicks = [0 0.5 1 1.5 2];
satslider.ValueChangedFcn = @updateImage
function updateImage(satslider,~)
% Read the current saturation value from the slider
saturationFactor = satslider.Value;
% Convert the image to HSV color space
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
% Update the saturation (S)
hsvImage(:, :, 2) = hsvImage(:, :, 2) * saturationFactor;
% Convert the modified image back to RGB color space
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
% Display the updated image
imshow(outputImage);
title([‘Saturation Factor: ‘ num2str(saturationFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
sharpslider = uislider;
sharpslider.Position = [150 20 300 3];
sharpslider.Limits = [0 2];
sharpslider.Value = 1;
sharpslider.MajorTicks = [0 0.5 1 1.5 2];
sharpslider.ValueChangedFcn = @updateImage;
function updateImage(sharpslider,~)
sharpenFactor = sharpslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imsharpen(inputImage, ‘Amount’, sharpenFactor);
% Display the updated image
imshow(outputImage);
title([‘sharpenFactor: ‘ num2str(sharpenFactor)]);
end I have 3 different sliders doing 3 different things and I’m trying to have all the things being done to it in one function at the same time. I’ve tried many different things and I still don’t know how. If anybody could provide some insight that would be greatly appreciated.
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
conslider = uislider;
conslider.Position = [150 20 300 3];
conslider.Limits = [0 2];
conslider.Value = 1;
conslider.MajorTicks = [0 0.5 1 1.5 2];
conslider.ValueChangedFcn = @updateImage;
function updateImage(conslider,~)
contrastFactor = conslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imadjust(outputImage, [], [], contrastFactor);
% Display the updated image
imshow(outputImage);
title([‘contrastFactor: ‘ num2str(contrastFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
% Developing a slider to adjust the saturation
satslider = uislider;
satslider.Position = [150 20 300 3];
satslider.Limits = [0 2];
satslider.Value = 1;
satslider.MajorTicks = [0 0.5 1 1.5 2];
satslider.ValueChangedFcn = @updateImage
function updateImage(satslider,~)
% Read the current saturation value from the slider
saturationFactor = satslider.Value;
% Convert the image to HSV color space
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
% Update the saturation (S)
hsvImage(:, :, 2) = hsvImage(:, :, 2) * saturationFactor;
% Convert the modified image back to RGB color space
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
% Display the updated image
imshow(outputImage);
title([‘Saturation Factor: ‘ num2str(saturationFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
sharpslider = uislider;
sharpslider.Position = [150 20 300 3];
sharpslider.Limits = [0 2];
sharpslider.Value = 1;
sharpslider.MajorTicks = [0 0.5 1 1.5 2];
sharpslider.ValueChangedFcn = @updateImage;
function updateImage(sharpslider,~)
sharpenFactor = sharpslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imsharpen(inputImage, ‘Amount’, sharpenFactor);
% Display the updated image
imshow(outputImage);
title([‘sharpenFactor: ‘ num2str(sharpenFactor)]);
end sliders MATLAB Answers — New Questions
Observations being read as number of columns instead of rows
Before splitting my data into training, validation, and testing, the code worked fine. After the split, trainnet begins reading the observations as the number of columns instead of by the number of rows. I checked the size of the array files and they are the same size the arrays were before I added a data split. I do not understand why trainnet starts reading the arrays differently. Any help would be appreciated.
Error message:
Error using trainnet
Error forming validation data mini-batch.
Error in MainCode6 (line 40)
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);
Caused by:
Number of observations in predictors (6) and targets (1) must match. Check that the data and network are
consistent.
% Script Number One
all = readtable(excelFile,"Sheet","Nsplit6",’VariableNamingRule’,’preserve’);
train_ratio = 0.8;
val_ratio = 0.1;
test_ratio = 0.1;
num_samples = size(all, 1);
indices = randperm(num_samples);
num_train = floor(train_ratio * num_samples);
num_val = floor(val_ratio * num_samples);
num_test = num_samples – num_train – num_val;
train_indices = indices(1:num_train);
val_indices = indices(num_train+1:num_train+num_val);
test_indices = indices(num_train+num_val+1:end);
train_data = all(train_indices, :);
val_data = all(val_indices, :);
test_data = all(test_indices, :);
X_train = train_data(:, 1:end-1);
Y_train = train_data(:, end);
X_val = val_data(:, 1:end-1);
Y_val = val_data(:, end);
X_test = test_data(:, 1:end-1);
Y_test = test_data(:, end);
stan_x_train = table2array(X_train);
stan_y_train = table2array(Y_train);
stan_x_val = table2array(X_val);
stan_y_val = table2array(Y_val);
stan_x_test = table2array(X_test);
stan_y_test = table2array(Y_test);
%Script number two
inputSize = 6;
hiddenLayerSize1 = 40;
hiddenLayerSize2 = 20;
hiddenLayerSize3 = 10;
outputSize = 1;
layers = [
featureInputLayer(inputSize)
fullyConnectedLayer(hiddenLayerSize1, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(hiddenLayerSize2, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(hiddenLayerSize3, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu3’)
fullyConnectedLayer(outputSize, ‘Name’, ‘output’)
];
net = dlnetwork(layers);
opts = trainingOptions(‘adam’, …
‘InitialLearnRate’, 0.01, …
‘MaxEpochs’, 200, …
‘MiniBatchSize’, 20, …
‘ValidationData’, {stan_x_val’, stan_y_val’}, …
‘ValidationFrequency’, 20, …
‘Verbose’, true …
);
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);Before splitting my data into training, validation, and testing, the code worked fine. After the split, trainnet begins reading the observations as the number of columns instead of by the number of rows. I checked the size of the array files and they are the same size the arrays were before I added a data split. I do not understand why trainnet starts reading the arrays differently. Any help would be appreciated.
Error message:
Error using trainnet
Error forming validation data mini-batch.
Error in MainCode6 (line 40)
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);
Caused by:
Number of observations in predictors (6) and targets (1) must match. Check that the data and network are
consistent.
% Script Number One
all = readtable(excelFile,"Sheet","Nsplit6",’VariableNamingRule’,’preserve’);
train_ratio = 0.8;
val_ratio = 0.1;
test_ratio = 0.1;
num_samples = size(all, 1);
indices = randperm(num_samples);
num_train = floor(train_ratio * num_samples);
num_val = floor(val_ratio * num_samples);
num_test = num_samples – num_train – num_val;
train_indices = indices(1:num_train);
val_indices = indices(num_train+1:num_train+num_val);
test_indices = indices(num_train+num_val+1:end);
train_data = all(train_indices, :);
val_data = all(val_indices, :);
test_data = all(test_indices, :);
X_train = train_data(:, 1:end-1);
Y_train = train_data(:, end);
X_val = val_data(:, 1:end-1);
Y_val = val_data(:, end);
X_test = test_data(:, 1:end-1);
Y_test = test_data(:, end);
stan_x_train = table2array(X_train);
stan_y_train = table2array(Y_train);
stan_x_val = table2array(X_val);
stan_y_val = table2array(Y_val);
stan_x_test = table2array(X_test);
stan_y_test = table2array(Y_test);
%Script number two
inputSize = 6;
hiddenLayerSize1 = 40;
hiddenLayerSize2 = 20;
hiddenLayerSize3 = 10;
outputSize = 1;
layers = [
featureInputLayer(inputSize)
fullyConnectedLayer(hiddenLayerSize1, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(hiddenLayerSize2, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(hiddenLayerSize3, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu3’)
fullyConnectedLayer(outputSize, ‘Name’, ‘output’)
];
net = dlnetwork(layers);
opts = trainingOptions(‘adam’, …
‘InitialLearnRate’, 0.01, …
‘MaxEpochs’, 200, …
‘MiniBatchSize’, 20, …
‘ValidationData’, {stan_x_val’, stan_y_val’}, …
‘ValidationFrequency’, 20, …
‘Verbose’, true …
);
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts); Before splitting my data into training, validation, and testing, the code worked fine. After the split, trainnet begins reading the observations as the number of columns instead of by the number of rows. I checked the size of the array files and they are the same size the arrays were before I added a data split. I do not understand why trainnet starts reading the arrays differently. Any help would be appreciated.
Error message:
Error using trainnet
Error forming validation data mini-batch.
Error in MainCode6 (line 40)
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);
Caused by:
Number of observations in predictors (6) and targets (1) must match. Check that the data and network are
consistent.
% Script Number One
all = readtable(excelFile,"Sheet","Nsplit6",’VariableNamingRule’,’preserve’);
train_ratio = 0.8;
val_ratio = 0.1;
test_ratio = 0.1;
num_samples = size(all, 1);
indices = randperm(num_samples);
num_train = floor(train_ratio * num_samples);
num_val = floor(val_ratio * num_samples);
num_test = num_samples – num_train – num_val;
train_indices = indices(1:num_train);
val_indices = indices(num_train+1:num_train+num_val);
test_indices = indices(num_train+num_val+1:end);
train_data = all(train_indices, :);
val_data = all(val_indices, :);
test_data = all(test_indices, :);
X_train = train_data(:, 1:end-1);
Y_train = train_data(:, end);
X_val = val_data(:, 1:end-1);
Y_val = val_data(:, end);
X_test = test_data(:, 1:end-1);
Y_test = test_data(:, end);
stan_x_train = table2array(X_train);
stan_y_train = table2array(Y_train);
stan_x_val = table2array(X_val);
stan_y_val = table2array(Y_val);
stan_x_test = table2array(X_test);
stan_y_test = table2array(Y_test);
%Script number two
inputSize = 6;
hiddenLayerSize1 = 40;
hiddenLayerSize2 = 20;
hiddenLayerSize3 = 10;
outputSize = 1;
layers = [
featureInputLayer(inputSize)
fullyConnectedLayer(hiddenLayerSize1, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(hiddenLayerSize2, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(hiddenLayerSize3, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu3’)
fullyConnectedLayer(outputSize, ‘Name’, ‘output’)
];
net = dlnetwork(layers);
opts = trainingOptions(‘adam’, …
‘InitialLearnRate’, 0.01, …
‘MaxEpochs’, 200, …
‘MiniBatchSize’, 20, …
‘ValidationData’, {stan_x_val’, stan_y_val’}, …
‘ValidationFrequency’, 20, …
‘Verbose’, true …
);
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts); dlnetwork, observation error, ann MATLAB Answers — New Questions
Need help figuring out why this nested function is not working
function [imgstruct,xyzuvwcrm] = IMGHandle(inputArg1)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
files = inputArg1;
count = 1;
for k = 1:length(files)
%[h,d]=svecread(files(k).name)
varargout = svec2(files(k).name); %Pass files into function to get img struc
% for i = 1:8
% table(:,i) = varargout(:,:,i);
% end
%Adds name of file to struct
xyzuvwcrm(k).name = files(k).name;
for i = 1:8
for x = 1:54
for y = 1:73
xyzuvwcrm(k).data(count,i) = varargout(x,y,i); %Read matrix val to table
count = count +1; %Counting pixels in the image
end
end
count = 1;
end
%Compute the magnitude of u,v,w and insert into column 9 of xyzuvwcrm
for l = 1:size(xyzuvwcrm(k).data,1)
xyzuvwcrm(k).data(l,9) = sqrt(sum((xyzuvwcrm(k).data(l,4:6)).^2));
end
%Creates the Image pixel structure
xyzuvwcrm(k).data = array2table(xyzuvwcrm(k).data,…
‘VariableNames’,["x mm","y mm","z mm","u m/s","v m/s","w m/s",…
"CHC","R Err","Magnitude"]);
imgstruct(k).name = files(k).name;
imgstruct(k).data = varargout ;%(:,:,i)
end
function varargout = svec2(varargin)
msg = nargchk(1,3,nargin); if ~isempty(msg), error(msg), end;
% Defaults:
if nargin < 3
varargin{3} = 8; % default columns value (13/08/01)
if nargin < 2
varargin{2} = 1; % default number of header lins
end
end
% Assign variables
name = varargin{1};
% append an extension if the user neglected to include it
headerlines = 1;
columns = 8;
% this seems like it would cause as many problems as it might fix.
if isempty(strfind(lower(name),’.v3d’))
name = strcat(name,’.v3D’);
end
% Read the header
fid = fopen(name,’r’);
if fid<0
error(‘File not found’);
end
hdr = fgetl(fid);
fclose(fid);
% Parse the header
% i’m terrible at using regex safely,
% so take this with a grain of salt
hdr = lower(hdr);
i = regexp(hdr,’i=(d+)’,’tokens’);
i = str2double(i{1}{1});
j = regexp(hdr,’j=(d+)’,’tokens’);
j = str2double(j{1}{1});
k = regexp(hdr,’k=(d+)’,’tokens’);
k = str2double(k{1}{1});
% read everything using a convenience tool
data = readmatrix(name,’filetype’,’text’, …
‘expectednumvariables’,columns, …
‘numheaderlines’,headerlines);
badind = find(data>9e9);
if ~isempty(badind), data(badind) = 0; warning(sprintf(‘Bad %d points’,length(badind))); end;
% then reshape
% i don’t know which way this is supposed to be oriented
data = reshape(data,i,j,[]);
data = permute(data,[2 1 3]);
if nargout == 1
varargout{1} = data;
elseif nargout == 2
varargout{1} = hdr;
varargout{2} = data;
elseif nargout == 4
varargout{1} = hdr;
varargout{2} = data;
varargout{3} = str2num(i);
varargout{4} = str2num(j);
varargout{5} = str2num(k);
else
warning(‘Wrong number of outputs’) ;
end
end
end
As you can see from the function above IMGHandle is the main function which uses the function svec2 defined within it. I have made sure that all files are within the same folder and this is the current folder. Have restarted matlab to try to update cache etc.
Currently the output I am getting when trying to pass a struct into IMGHandle is the following:
Error using pivdatareadertest>IMGHandle/svec2
File not found
Error in pivdatareadertest>IMGHandle (line 254)
varargout = svec2(files(k).name); %Pass files into function to get img struc
Error in pivdatareadertest (line 55)
[imgstruct,xyzuvwcrm] = IMGHandle(Class4FS20HZ);
Thank you.function [imgstruct,xyzuvwcrm] = IMGHandle(inputArg1)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
files = inputArg1;
count = 1;
for k = 1:length(files)
%[h,d]=svecread(files(k).name)
varargout = svec2(files(k).name); %Pass files into function to get img struc
% for i = 1:8
% table(:,i) = varargout(:,:,i);
% end
%Adds name of file to struct
xyzuvwcrm(k).name = files(k).name;
for i = 1:8
for x = 1:54
for y = 1:73
xyzuvwcrm(k).data(count,i) = varargout(x,y,i); %Read matrix val to table
count = count +1; %Counting pixels in the image
end
end
count = 1;
end
%Compute the magnitude of u,v,w and insert into column 9 of xyzuvwcrm
for l = 1:size(xyzuvwcrm(k).data,1)
xyzuvwcrm(k).data(l,9) = sqrt(sum((xyzuvwcrm(k).data(l,4:6)).^2));
end
%Creates the Image pixel structure
xyzuvwcrm(k).data = array2table(xyzuvwcrm(k).data,…
‘VariableNames’,["x mm","y mm","z mm","u m/s","v m/s","w m/s",…
"CHC","R Err","Magnitude"]);
imgstruct(k).name = files(k).name;
imgstruct(k).data = varargout ;%(:,:,i)
end
function varargout = svec2(varargin)
msg = nargchk(1,3,nargin); if ~isempty(msg), error(msg), end;
% Defaults:
if nargin < 3
varargin{3} = 8; % default columns value (13/08/01)
if nargin < 2
varargin{2} = 1; % default number of header lins
end
end
% Assign variables
name = varargin{1};
% append an extension if the user neglected to include it
headerlines = 1;
columns = 8;
% this seems like it would cause as many problems as it might fix.
if isempty(strfind(lower(name),’.v3d’))
name = strcat(name,’.v3D’);
end
% Read the header
fid = fopen(name,’r’);
if fid<0
error(‘File not found’);
end
hdr = fgetl(fid);
fclose(fid);
% Parse the header
% i’m terrible at using regex safely,
% so take this with a grain of salt
hdr = lower(hdr);
i = regexp(hdr,’i=(d+)’,’tokens’);
i = str2double(i{1}{1});
j = regexp(hdr,’j=(d+)’,’tokens’);
j = str2double(j{1}{1});
k = regexp(hdr,’k=(d+)’,’tokens’);
k = str2double(k{1}{1});
% read everything using a convenience tool
data = readmatrix(name,’filetype’,’text’, …
‘expectednumvariables’,columns, …
‘numheaderlines’,headerlines);
badind = find(data>9e9);
if ~isempty(badind), data(badind) = 0; warning(sprintf(‘Bad %d points’,length(badind))); end;
% then reshape
% i don’t know which way this is supposed to be oriented
data = reshape(data,i,j,[]);
data = permute(data,[2 1 3]);
if nargout == 1
varargout{1} = data;
elseif nargout == 2
varargout{1} = hdr;
varargout{2} = data;
elseif nargout == 4
varargout{1} = hdr;
varargout{2} = data;
varargout{3} = str2num(i);
varargout{4} = str2num(j);
varargout{5} = str2num(k);
else
warning(‘Wrong number of outputs’) ;
end
end
end
As you can see from the function above IMGHandle is the main function which uses the function svec2 defined within it. I have made sure that all files are within the same folder and this is the current folder. Have restarted matlab to try to update cache etc.
Currently the output I am getting when trying to pass a struct into IMGHandle is the following:
Error using pivdatareadertest>IMGHandle/svec2
File not found
Error in pivdatareadertest>IMGHandle (line 254)
varargout = svec2(files(k).name); %Pass files into function to get img struc
Error in pivdatareadertest (line 55)
[imgstruct,xyzuvwcrm] = IMGHandle(Class4FS20HZ);
Thank you. function [imgstruct,xyzuvwcrm] = IMGHandle(inputArg1)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
files = inputArg1;
count = 1;
for k = 1:length(files)
%[h,d]=svecread(files(k).name)
varargout = svec2(files(k).name); %Pass files into function to get img struc
% for i = 1:8
% table(:,i) = varargout(:,:,i);
% end
%Adds name of file to struct
xyzuvwcrm(k).name = files(k).name;
for i = 1:8
for x = 1:54
for y = 1:73
xyzuvwcrm(k).data(count,i) = varargout(x,y,i); %Read matrix val to table
count = count +1; %Counting pixels in the image
end
end
count = 1;
end
%Compute the magnitude of u,v,w and insert into column 9 of xyzuvwcrm
for l = 1:size(xyzuvwcrm(k).data,1)
xyzuvwcrm(k).data(l,9) = sqrt(sum((xyzuvwcrm(k).data(l,4:6)).^2));
end
%Creates the Image pixel structure
xyzuvwcrm(k).data = array2table(xyzuvwcrm(k).data,…
‘VariableNames’,["x mm","y mm","z mm","u m/s","v m/s","w m/s",…
"CHC","R Err","Magnitude"]);
imgstruct(k).name = files(k).name;
imgstruct(k).data = varargout ;%(:,:,i)
end
function varargout = svec2(varargin)
msg = nargchk(1,3,nargin); if ~isempty(msg), error(msg), end;
% Defaults:
if nargin < 3
varargin{3} = 8; % default columns value (13/08/01)
if nargin < 2
varargin{2} = 1; % default number of header lins
end
end
% Assign variables
name = varargin{1};
% append an extension if the user neglected to include it
headerlines = 1;
columns = 8;
% this seems like it would cause as many problems as it might fix.
if isempty(strfind(lower(name),’.v3d’))
name = strcat(name,’.v3D’);
end
% Read the header
fid = fopen(name,’r’);
if fid<0
error(‘File not found’);
end
hdr = fgetl(fid);
fclose(fid);
% Parse the header
% i’m terrible at using regex safely,
% so take this with a grain of salt
hdr = lower(hdr);
i = regexp(hdr,’i=(d+)’,’tokens’);
i = str2double(i{1}{1});
j = regexp(hdr,’j=(d+)’,’tokens’);
j = str2double(j{1}{1});
k = regexp(hdr,’k=(d+)’,’tokens’);
k = str2double(k{1}{1});
% read everything using a convenience tool
data = readmatrix(name,’filetype’,’text’, …
‘expectednumvariables’,columns, …
‘numheaderlines’,headerlines);
badind = find(data>9e9);
if ~isempty(badind), data(badind) = 0; warning(sprintf(‘Bad %d points’,length(badind))); end;
% then reshape
% i don’t know which way this is supposed to be oriented
data = reshape(data,i,j,[]);
data = permute(data,[2 1 3]);
if nargout == 1
varargout{1} = data;
elseif nargout == 2
varargout{1} = hdr;
varargout{2} = data;
elseif nargout == 4
varargout{1} = hdr;
varargout{2} = data;
varargout{3} = str2num(i);
varargout{4} = str2num(j);
varargout{5} = str2num(k);
else
warning(‘Wrong number of outputs’) ;
end
end
end
As you can see from the function above IMGHandle is the main function which uses the function svec2 defined within it. I have made sure that all files are within the same folder and this is the current folder. Have restarted matlab to try to update cache etc.
Currently the output I am getting when trying to pass a struct into IMGHandle is the following:
Error using pivdatareadertest>IMGHandle/svec2
File not found
Error in pivdatareadertest>IMGHandle (line 254)
varargout = svec2(files(k).name); %Pass files into function to get img struc
Error in pivdatareadertest (line 55)
[imgstruct,xyzuvwcrm] = IMGHandle(Class4FS20HZ);
Thank you. functions MATLAB Answers — New Questions
Seeking Help to Optimize MATLAB Function for reducing running time
Dear MATLAB Community,
I hope this message finds you well. I’m currently working on a project that involves optimizing a MATLAB function for improved performance, and I’m reaching out to seek your valuable assistance.
The function is a crucial component of my project. While it serves its purpose, I believe there is room for enhancement in terms of its execution speed. Now it takes more than 1 hours but I want if we can do it in 20-25 min.
I’ve explored various optimization techniques, including vectorization and sparse matrix usage, but I’m still encountering performance bottlenecks.
If you have experience or expertise in optimizing MATLAB functions or tackling similar challenges, I would greatly appreciate any insights, suggestions, or optimizations you could offer.
Your assistance would not only benefit my project but also contribute to the collective knowledge and expertise of the MATLAB community.
Thank you for considering my request, and I look forward to any guidance or assistance you can provid. der1 and der2 are large file more than 5 mb. So I am unable to attach them. each is a cell of {10980*1} and each elemet of 10980*10980. thanks
function J = customJ(der1, der2, smat, DTM)
% %Calculate system matrix
% der1=der1;
% der2=der2;
% smat =smat;
% phi =phi;
% z = z;
load(‘der1.mat’)
load(‘der2.mat’)
load(‘smat.mat’)
load(‘phi.mat’)
load(‘z.mat’)
Ismart =inv(smat);
n = 10980;
% Preallocate memory for derivative matrices
ns = 28;
nd = 28;
%Jmua = zeros(ns * nd, n);
%Jmus = zeros(ns * nd, n);
Jmua = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
Jmus = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
% Calculate full matrices directly
for ii = 1:n
% Display progress
disp([‘column wise: ‘ num2str(round(ii/n*100)) ‘%’])
dm0dmua = -Ismart * (der1{ii} * phi);
dm0dmus = -Ismart * (der2{ii} * phi);
% Calculate Jmua and Jmus directly
temp1 = DTM.’ * dm0dmua;
temp2 = DTM.’ * dm0dmus;
temp3 = z;
Jmua(:,ii) = temp1(:)./temp3(:);
Jmus(:,ii) = temp2(:)./temp3(:);
end
% Concatenate Jmua and Jmus
J = [real([Jmua, Jmus]); imag([Jmua, Jmus])];
endDear MATLAB Community,
I hope this message finds you well. I’m currently working on a project that involves optimizing a MATLAB function for improved performance, and I’m reaching out to seek your valuable assistance.
The function is a crucial component of my project. While it serves its purpose, I believe there is room for enhancement in terms of its execution speed. Now it takes more than 1 hours but I want if we can do it in 20-25 min.
I’ve explored various optimization techniques, including vectorization and sparse matrix usage, but I’m still encountering performance bottlenecks.
If you have experience or expertise in optimizing MATLAB functions or tackling similar challenges, I would greatly appreciate any insights, suggestions, or optimizations you could offer.
Your assistance would not only benefit my project but also contribute to the collective knowledge and expertise of the MATLAB community.
Thank you for considering my request, and I look forward to any guidance or assistance you can provid. der1 and der2 are large file more than 5 mb. So I am unable to attach them. each is a cell of {10980*1} and each elemet of 10980*10980. thanks
function J = customJ(der1, der2, smat, DTM)
% %Calculate system matrix
% der1=der1;
% der2=der2;
% smat =smat;
% phi =phi;
% z = z;
load(‘der1.mat’)
load(‘der2.mat’)
load(‘smat.mat’)
load(‘phi.mat’)
load(‘z.mat’)
Ismart =inv(smat);
n = 10980;
% Preallocate memory for derivative matrices
ns = 28;
nd = 28;
%Jmua = zeros(ns * nd, n);
%Jmus = zeros(ns * nd, n);
Jmua = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
Jmus = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
% Calculate full matrices directly
for ii = 1:n
% Display progress
disp([‘column wise: ‘ num2str(round(ii/n*100)) ‘%’])
dm0dmua = -Ismart * (der1{ii} * phi);
dm0dmus = -Ismart * (der2{ii} * phi);
% Calculate Jmua and Jmus directly
temp1 = DTM.’ * dm0dmua;
temp2 = DTM.’ * dm0dmus;
temp3 = z;
Jmua(:,ii) = temp1(:)./temp3(:);
Jmus(:,ii) = temp2(:)./temp3(:);
end
% Concatenate Jmua and Jmus
J = [real([Jmua, Jmus]); imag([Jmua, Jmus])];
end Dear MATLAB Community,
I hope this message finds you well. I’m currently working on a project that involves optimizing a MATLAB function for improved performance, and I’m reaching out to seek your valuable assistance.
The function is a crucial component of my project. While it serves its purpose, I believe there is room for enhancement in terms of its execution speed. Now it takes more than 1 hours but I want if we can do it in 20-25 min.
I’ve explored various optimization techniques, including vectorization and sparse matrix usage, but I’m still encountering performance bottlenecks.
If you have experience or expertise in optimizing MATLAB functions or tackling similar challenges, I would greatly appreciate any insights, suggestions, or optimizations you could offer.
Your assistance would not only benefit my project but also contribute to the collective knowledge and expertise of the MATLAB community.
Thank you for considering my request, and I look forward to any guidance or assistance you can provid. der1 and der2 are large file more than 5 mb. So I am unable to attach them. each is a cell of {10980*1} and each elemet of 10980*10980. thanks
function J = customJ(der1, der2, smat, DTM)
% %Calculate system matrix
% der1=der1;
% der2=der2;
% smat =smat;
% phi =phi;
% z = z;
load(‘der1.mat’)
load(‘der2.mat’)
load(‘smat.mat’)
load(‘phi.mat’)
load(‘z.mat’)
Ismart =inv(smat);
n = 10980;
% Preallocate memory for derivative matrices
ns = 28;
nd = 28;
%Jmua = zeros(ns * nd, n);
%Jmus = zeros(ns * nd, n);
Jmua = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
Jmus = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
% Calculate full matrices directly
for ii = 1:n
% Display progress
disp([‘column wise: ‘ num2str(round(ii/n*100)) ‘%’])
dm0dmua = -Ismart * (der1{ii} * phi);
dm0dmus = -Ismart * (der2{ii} * phi);
% Calculate Jmua and Jmus directly
temp1 = DTM.’ * dm0dmua;
temp2 = DTM.’ * dm0dmus;
temp3 = z;
Jmua(:,ii) = temp1(:)./temp3(:);
Jmus(:,ii) = temp2(:)./temp3(:);
end
% Concatenate Jmua and Jmus
J = [real([Jmua, Jmus]); imag([Jmua, Jmus])];
end matrix, multiplication, sparse MATLAB Answers — New Questions
How to detect whether a figure is created by uifigure()
I have the following in my startup.m file,
set(groot,’defaultFigureCreateFcn’,@(fig, ~)addToolbarExplorationButtons(fig));
which throws an error when a uifigure is created,
fig = uifigure;
Error using matlab.ui.Figure/set
Functionality not supported with figures created with
the uifigure function.
So, the question becomes, how can I pre-detect whether fig has been created by uifigure() as opposed to figure()? There don’t appear to be separate classes reserved for the two,
>> class(figure)
ans =
‘matlab.ui.Figure’
>> class(uifigure)
ans =
‘matlab.ui.Figure’I have the following in my startup.m file,
set(groot,’defaultFigureCreateFcn’,@(fig, ~)addToolbarExplorationButtons(fig));
which throws an error when a uifigure is created,
fig = uifigure;
Error using matlab.ui.Figure/set
Functionality not supported with figures created with
the uifigure function.
So, the question becomes, how can I pre-detect whether fig has been created by uifigure() as opposed to figure()? There don’t appear to be separate classes reserved for the two,
>> class(figure)
ans =
‘matlab.ui.Figure’
>> class(uifigure)
ans =
‘matlab.ui.Figure’ I have the following in my startup.m file,
set(groot,’defaultFigureCreateFcn’,@(fig, ~)addToolbarExplorationButtons(fig));
which throws an error when a uifigure is created,
fig = uifigure;
Error using matlab.ui.Figure/set
Functionality not supported with figures created with
the uifigure function.
So, the question becomes, how can I pre-detect whether fig has been created by uifigure() as opposed to figure()? There don’t appear to be separate classes reserved for the two,
>> class(figure)
ans =
‘matlab.ui.Figure’
>> class(uifigure)
ans =
‘matlab.ui.Figure’ figure, uifigure, exploration buttons, graphics, app, gui MATLAB Answers — New Questions
How can I generate code from the system I’ve designed in the fuzzy logic designer?
Hello everyone 🙂
I am currently facing a problem to generate the coding from fuzzy logic designer. . I’m using FIS mamdani type-1, after inserted all the data such as input, rules, and output i don’t know how to generate the coding. How can I generate code from this system? Can someone help me?
Thank you in advance.Hello everyone 🙂
I am currently facing a problem to generate the coding from fuzzy logic designer. . I’m using FIS mamdani type-1, after inserted all the data such as input, rules, and output i don’t know how to generate the coding. How can I generate code from this system? Can someone help me?
Thank you in advance. Hello everyone 🙂
I am currently facing a problem to generate the coding from fuzzy logic designer. . I’m using FIS mamdani type-1, after inserted all the data such as input, rules, and output i don’t know how to generate the coding. How can I generate code from this system? Can someone help me?
Thank you in advance. fis, fuzzy logic designer, deffuzzification MATLAB Answers — New Questions
Solving a System of Nonlinear Equations n Times With Different Values
Hi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can’t find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) – z1(i)
F(2) = x(1) + x(2)./x(1) – z2(i)
end
endHi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can’t find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) – z1(i)
F(2) = x(1) + x(2)./x(1) – z2(i)
end
end Hi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can’t find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) – z1(i)
F(2) = x(1) + x(2)./x(1) – z2(i)
end
end nonlinear system, fsolve MATLAB Answers — New Questions