Category: Matlab
Category Archives: Matlab
Computer uses only 21% of cpu when running multithreading in simulink
I made a simulink spice model for a circuit and it is taking around 30 minutes to compile, I thought it was normal, but checking windows task manager it seems that only one thread of my cpu is at it’s maximum capacity, i tried using different configurations of workers and threads per worker, but nothing work it is still using arount 21% of the total of my CPU.
My simulink model has only one .slx
I am using this code for the parallel computing part
bdclose all;
%proj = openProject(‘.C:UsersfernaDownloadshalfBridgeTest.slx’);
model = ‘DownloadshalfBridgeTest.slx’;
open_system(model);
modelN = ‘halfBridgeTest’;
in = Simulink.SimulationInput(modelN);
parpool(‘LocalProfile1’)
tic; out = parsim(in, ‘UseFastRestart’,’on’); toc
delete(gcp(‘nocreate’));I made a simulink spice model for a circuit and it is taking around 30 minutes to compile, I thought it was normal, but checking windows task manager it seems that only one thread of my cpu is at it’s maximum capacity, i tried using different configurations of workers and threads per worker, but nothing work it is still using arount 21% of the total of my CPU.
My simulink model has only one .slx
I am using this code for the parallel computing part
bdclose all;
%proj = openProject(‘.C:UsersfernaDownloadshalfBridgeTest.slx’);
model = ‘DownloadshalfBridgeTest.slx’;
open_system(model);
modelN = ‘halfBridgeTest’;
in = Simulink.SimulationInput(modelN);
parpool(‘LocalProfile1’)
tic; out = parsim(in, ‘UseFastRestart’,’on’); toc
delete(gcp(‘nocreate’)); I made a simulink spice model for a circuit and it is taking around 30 minutes to compile, I thought it was normal, but checking windows task manager it seems that only one thread of my cpu is at it’s maximum capacity, i tried using different configurations of workers and threads per worker, but nothing work it is still using arount 21% of the total of my CPU.
My simulink model has only one .slx
I am using this code for the parallel computing part
bdclose all;
%proj = openProject(‘.C:UsersfernaDownloadshalfBridgeTest.slx’);
model = ‘DownloadshalfBridgeTest.slx’;
open_system(model);
modelN = ‘halfBridgeTest’;
in = Simulink.SimulationInput(modelN);
parpool(‘LocalProfile1’)
tic; out = parsim(in, ‘UseFastRestart’,’on’); toc
delete(gcp(‘nocreate’)); parallel computing, parallel computing toolbox, simulink MATLAB Answers — New Questions
inverse LaPlace transform of confluent hypergeometric function
hello, I want to calculate the inverse laplace transform of a characteristic function
this is the fourier transform of h(x), which is converted to Laplace transform with p = -i*t
from here we make a characteristic function which is
this characteristic function is converted to hypergeometric function
I have to get the inverse laplace transform of this function, I have written the following code:
N = 3; x_bar = 2.5; a = 1.3; b = 13; c = a+b;
syms s t
p = -1*1j*s
z = -1*((N*x_bar*(c/a)*p)/(p+1))
h = hypergeom(a,c,z)
C_slow = h/((p+1)^N)
f(t) = ilaplace(C_slow)
output of code:
z =
-(s*165i)/(2*(- 1 + s*1i))
h =
hypergeom(13/10, 143/10, -(s*165i)/(2*(- 1 + s*1i)))
do we have to put the vlaue of ”s” to evalute the hypergeom function? I don’t know what i am missing here…any help would be appreciatedhello, I want to calculate the inverse laplace transform of a characteristic function
this is the fourier transform of h(x), which is converted to Laplace transform with p = -i*t
from here we make a characteristic function which is
this characteristic function is converted to hypergeometric function
I have to get the inverse laplace transform of this function, I have written the following code:
N = 3; x_bar = 2.5; a = 1.3; b = 13; c = a+b;
syms s t
p = -1*1j*s
z = -1*((N*x_bar*(c/a)*p)/(p+1))
h = hypergeom(a,c,z)
C_slow = h/((p+1)^N)
f(t) = ilaplace(C_slow)
output of code:
z =
-(s*165i)/(2*(- 1 + s*1i))
h =
hypergeom(13/10, 143/10, -(s*165i)/(2*(- 1 + s*1i)))
do we have to put the vlaue of ”s” to evalute the hypergeom function? I don’t know what i am missing here…any help would be appreciated hello, I want to calculate the inverse laplace transform of a characteristic function
this is the fourier transform of h(x), which is converted to Laplace transform with p = -i*t
from here we make a characteristic function which is
this characteristic function is converted to hypergeometric function
I have to get the inverse laplace transform of this function, I have written the following code:
N = 3; x_bar = 2.5; a = 1.3; b = 13; c = a+b;
syms s t
p = -1*1j*s
z = -1*((N*x_bar*(c/a)*p)/(p+1))
h = hypergeom(a,c,z)
C_slow = h/((p+1)^N)
f(t) = ilaplace(C_slow)
output of code:
z =
-(s*165i)/(2*(- 1 + s*1i))
h =
hypergeom(13/10, 143/10, -(s*165i)/(2*(- 1 + s*1i)))
do we have to put the vlaue of ”s” to evalute the hypergeom function? I don’t know what i am missing here…any help would be appreciated laplace transform, hypergeometric function, swerling characteristic function MATLAB Answers — New Questions
Why such a fuss with ndgrid and meshgrid issues?
Folks,
In the world of artificial intelligence and more intelligent programming, I would like to see more intelligence put into place with how function like griddata, imagesc, pcolor, and surf interpret their inputs. There is an unfortunate degree of confusion that has persisted since the early 2000’s at least with how to interpret arrays in terms of Cartesian axes. I am troubled today with trying to understand how griddata is working on input that I setup using ndgrid. I appear to have something wrong, and earth layers are not dipping in the direction that I expect. The documentation says griddata can work with either meshgrid or griddata input, which makes my head spin given my understanding of both meshgrid and ndgrid. What is really troubling is that the Mathworks documentation routinely contains only simple examples where the person that created the documentation made "quicky" non-realistic examples where they simply created input arrays that had exactly the same x and y dimensions, which does not help anyone in my situation who is dealing with realistic inputs that do not have the same dimension lengths. I request that future documentation efforts spend a little extra time making non-symmetric input x and y arrays as examples.Folks,
In the world of artificial intelligence and more intelligent programming, I would like to see more intelligence put into place with how function like griddata, imagesc, pcolor, and surf interpret their inputs. There is an unfortunate degree of confusion that has persisted since the early 2000’s at least with how to interpret arrays in terms of Cartesian axes. I am troubled today with trying to understand how griddata is working on input that I setup using ndgrid. I appear to have something wrong, and earth layers are not dipping in the direction that I expect. The documentation says griddata can work with either meshgrid or griddata input, which makes my head spin given my understanding of both meshgrid and ndgrid. What is really troubling is that the Mathworks documentation routinely contains only simple examples where the person that created the documentation made "quicky" non-realistic examples where they simply created input arrays that had exactly the same x and y dimensions, which does not help anyone in my situation who is dealing with realistic inputs that do not have the same dimension lengths. I request that future documentation efforts spend a little extra time making non-symmetric input x and y arrays as examples. Folks,
In the world of artificial intelligence and more intelligent programming, I would like to see more intelligence put into place with how function like griddata, imagesc, pcolor, and surf interpret their inputs. There is an unfortunate degree of confusion that has persisted since the early 2000’s at least with how to interpret arrays in terms of Cartesian axes. I am troubled today with trying to understand how griddata is working on input that I setup using ndgrid. I appear to have something wrong, and earth layers are not dipping in the direction that I expect. The documentation says griddata can work with either meshgrid or griddata input, which makes my head spin given my understanding of both meshgrid and ndgrid. What is really troubling is that the Mathworks documentation routinely contains only simple examples where the person that created the documentation made "quicky" non-realistic examples where they simply created input arrays that had exactly the same x and y dimensions, which does not help anyone in my situation who is dealing with realistic inputs that do not have the same dimension lengths. I request that future documentation efforts spend a little extra time making non-symmetric input x and y arrays as examples. meshgrid, ndgrid, imagesc, pcolor, surf, griddata, slice, obliqueslice MATLAB Answers — New Questions
(bug)MATLAB Support Package for Apple iOS Sensors could’t work?
When I install "MATLAB Support Package for Apple iOS Sensors" successfully,then input in command line:
m = mobiledev
Failure to load the device plug-in.
I have tried other similar commands such as "mobiledevlist", which gives the same error. I’m looking forward to the official fix to solve the problem in time!
MATLAB 2024a,windows 10 22H2When I install "MATLAB Support Package for Apple iOS Sensors" successfully,then input in command line:
m = mobiledev
Failure to load the device plug-in.
I have tried other similar commands such as "mobiledevlist", which gives the same error. I’m looking forward to the official fix to solve the problem in time!
MATLAB 2024a,windows 10 22H2 When I install "MATLAB Support Package for Apple iOS Sensors" successfully,then input in command line:
m = mobiledev
Failure to load the device plug-in.
I have tried other similar commands such as "mobiledevlist", which gives the same error. I’m looking forward to the official fix to solve the problem in time!
MATLAB 2024a,windows 10 22H2 matlab, matlab mobile, sensors MATLAB Answers — New Questions
MATLAB HiDPI setting ignored on Linux (Ubuntu)
Hi,
I am running a fresh install of MATLAB R2022b on Ubuntu 22.04.
Laptop: HP Zbook Fury G7 (screen resolution 3840×2160)
GPU1: Intel Cometlake-H GT2
GPU2: NVidia Quadro T1000.
MATLAB install script was executed as sudo, as described here (link [MATLAB]). There have been several related questions in MATLAB Answers (link1, link2, and many more related to Windows) but none seem to work for this case.
Few observations:
If xrandr is not used, the scaling setting is completely ignored.
Executing the xrandr with the calculated DPI, seems to affect only the splash screen, but not the MATLAB interface.
After xrandr, changing the scaling setting in MATLAB affects the editor only (without restart). This is behavior is again lost after restart.
Changing permission (as suggested by one comment) in the ~/.matlab file, did not work.
Installing MATLAB as non-sudo yields the same results.
Anyone knows if there is anything else I could try? Besides lowering the screen resolution, since that results in blurriness.
Thanks!
Edit 1: Typo
Edit 2: Looking around it seems to be a permission issue. For testing purposes only, I added ‘root’ user to the license and when changing the scaling setting it is honored as expected. In the ~/.matlab folder for the root user, the main differences is the presense of *.mlsettings binary files. Although, giving full persmissions to the $USER for both ~/.matlab as well as /usr/local/MATLAB folder does not seem to affect the process in any way.
Current workaround: copying matlab.mlsettings file from the root to the user’s .matlab directory seems fix the issue. But this is far from a solution. Modyfing any setting of these settings/preferences require to first run matlab as root, make the modifitiations and then copy-paste the relevant *.mlsettings files. Will update when I have more.
Edit 3: A better workaround (no root needed): It seems that if a desktop launcher is used (matlab-support package), bash is not run in advance and MATLAB does not access the system enviroment variables, including the TMPDIR/TMP. Then (for some reason..) MATLAB can not access the /tmp/ folder and this is probably where things break. Two ways go around this are:
Run matlab from terminal where bashrc is already sourced (including for example a TMP var to an accessible folder, e.g. ~/.tmp/).
Or, change the default MATLAB tempdir. This is inspired from the workaround of ‘Invalid cross-device link (18)’ error I also exprerienced when trying to save a document (link3). Although, this setting is again lost after a restart, at least for me.Hi,
I am running a fresh install of MATLAB R2022b on Ubuntu 22.04.
Laptop: HP Zbook Fury G7 (screen resolution 3840×2160)
GPU1: Intel Cometlake-H GT2
GPU2: NVidia Quadro T1000.
MATLAB install script was executed as sudo, as described here (link [MATLAB]). There have been several related questions in MATLAB Answers (link1, link2, and many more related to Windows) but none seem to work for this case.
Few observations:
If xrandr is not used, the scaling setting is completely ignored.
Executing the xrandr with the calculated DPI, seems to affect only the splash screen, but not the MATLAB interface.
After xrandr, changing the scaling setting in MATLAB affects the editor only (without restart). This is behavior is again lost after restart.
Changing permission (as suggested by one comment) in the ~/.matlab file, did not work.
Installing MATLAB as non-sudo yields the same results.
Anyone knows if there is anything else I could try? Besides lowering the screen resolution, since that results in blurriness.
Thanks!
Edit 1: Typo
Edit 2: Looking around it seems to be a permission issue. For testing purposes only, I added ‘root’ user to the license and when changing the scaling setting it is honored as expected. In the ~/.matlab folder for the root user, the main differences is the presense of *.mlsettings binary files. Although, giving full persmissions to the $USER for both ~/.matlab as well as /usr/local/MATLAB folder does not seem to affect the process in any way.
Current workaround: copying matlab.mlsettings file from the root to the user’s .matlab directory seems fix the issue. But this is far from a solution. Modyfing any setting of these settings/preferences require to first run matlab as root, make the modifitiations and then copy-paste the relevant *.mlsettings files. Will update when I have more.
Edit 3: A better workaround (no root needed): It seems that if a desktop launcher is used (matlab-support package), bash is not run in advance and MATLAB does not access the system enviroment variables, including the TMPDIR/TMP. Then (for some reason..) MATLAB can not access the /tmp/ folder and this is probably where things break. Two ways go around this are:
Run matlab from terminal where bashrc is already sourced (including for example a TMP var to an accessible folder, e.g. ~/.tmp/).
Or, change the default MATLAB tempdir. This is inspired from the workaround of ‘Invalid cross-device link (18)’ error I also exprerienced when trying to save a document (link3). Although, this setting is again lost after a restart, at least for me. Hi,
I am running a fresh install of MATLAB R2022b on Ubuntu 22.04.
Laptop: HP Zbook Fury G7 (screen resolution 3840×2160)
GPU1: Intel Cometlake-H GT2
GPU2: NVidia Quadro T1000.
MATLAB install script was executed as sudo, as described here (link [MATLAB]). There have been several related questions in MATLAB Answers (link1, link2, and many more related to Windows) but none seem to work for this case.
Few observations:
If xrandr is not used, the scaling setting is completely ignored.
Executing the xrandr with the calculated DPI, seems to affect only the splash screen, but not the MATLAB interface.
After xrandr, changing the scaling setting in MATLAB affects the editor only (without restart). This is behavior is again lost after restart.
Changing permission (as suggested by one comment) in the ~/.matlab file, did not work.
Installing MATLAB as non-sudo yields the same results.
Anyone knows if there is anything else I could try? Besides lowering the screen resolution, since that results in blurriness.
Thanks!
Edit 1: Typo
Edit 2: Looking around it seems to be a permission issue. For testing purposes only, I added ‘root’ user to the license and when changing the scaling setting it is honored as expected. In the ~/.matlab folder for the root user, the main differences is the presense of *.mlsettings binary files. Although, giving full persmissions to the $USER for both ~/.matlab as well as /usr/local/MATLAB folder does not seem to affect the process in any way.
Current workaround: copying matlab.mlsettings file from the root to the user’s .matlab directory seems fix the issue. But this is far from a solution. Modyfing any setting of these settings/preferences require to first run matlab as root, make the modifitiations and then copy-paste the relevant *.mlsettings files. Will update when I have more.
Edit 3: A better workaround (no root needed): It seems that if a desktop launcher is used (matlab-support package), bash is not run in advance and MATLAB does not access the system enviroment variables, including the TMPDIR/TMP. Then (for some reason..) MATLAB can not access the /tmp/ folder and this is probably where things break. Two ways go around this are:
Run matlab from terminal where bashrc is already sourced (including for example a TMP var to an accessible folder, e.g. ~/.tmp/).
Or, change the default MATLAB tempdir. This is inspired from the workaround of ‘Invalid cross-device link (18)’ error I also exprerienced when trying to save a document (link3). Although, this setting is again lost after a restart, at least for me. hidpi, linux, ubuntu MATLAB Answers — New Questions
What is wrong with my FFT code?
I have this code, the plot looks correct but the values don’t come out right. I even tested an ideal sine wave, but it’s the same. which means the code is wrong, but I can’t figure out which part of the code is wrong. it looks correct to me. please help me out;
% Parameters
N = 8192; % Number of samples for FFT
fs = 10e9; % Sampling frequency (10 GHz)
harmonics = 3; % Number of harmonics to consider
% Extract 8192 samples from OUTPUT (assuming OUTPUT is already defined)
x = OUTPUT(1:N);
% Normalize data to unit magnitude
x = x / max(abs(x));
% Perform FFT
X = fft(x);
% Frequency axis
f_axis = (0:N-1) * fs / N; % Frequency axis from 0 to fs
% Remove DC component
X(1) = 0;
% Find dominant frequency component
[~, max_idx] = max(abs(X)); % Find the index of the maximum magnitude
% Calculate estimated signal frequency
f_signal = f_axis(max_idx); % Frequency corresponding to the maximum magnitude
% Calculate SNR correctly
signal_power = abs(X(max_idx))^2; % Power of the signal tone
noise_power = sum(abs(X).^2) – signal_power; % Total noise power (excluding signal tone)
SNR = 10*log10(signal_power / noise_power); % Signal-to-Noise Ratio in dB
% Calculate ENOB
ENOB = (SNR – 1.76) / 6.02;
% Calculate SFDR
SFDR_power = max(abs(X))^2; % Power of the largest spurious component (excluding DC)
SFDR = 10*log10(SFDR_power / signal_power); % Spurious Free Dynamic Range in dB
% Calculate THD correctly
THD_power = sum(abs(X(2:end)).^2); % Total harmonic distortion power (excluding signal and DC)
THD = 10*log10(THD_power / signal_power); % Total harmonic distortion in dB
% Plot FFT magnitude spectrum (folded, centered around fs/2)
figure;
plot(f_axis / 1e6, 20*log10(abs(X) / N)); % Plot in MHz and dB
xlabel(‘Frequency (MHz)’);
ylabel(‘Magnitude (dB/Hz)’);
title(‘FFT Magnitude Spectrum’);
grid on;
xlim([0 fs/2/1e6]); % Limit x-axis to 0 to fs/2 in MHz
% Mark signal tone and harmonics on the plot
hold on;
plot(f_signal / 1e6, 20*log10(abs(X(max_idx)) / N), ‘ro’, ‘MarkerSize’, 10, ‘LineWidth’, 2); % Mark signal tone
for i = 1:harmonics
harmonic_freq = i * f_signal;
[~, harmonic_bin] = min(abs(f_axis – harmonic_freq)); % Find nearest bin index
plot(f_axis(harmonic_bin) / 1e6, 20*log10(abs(X(harmonic_bin)) / N), ‘go’, ‘MarkerSize’, 10, ‘LineWidth’, 2); % Mark harmonics
end
hold off;
% Create legend for ENOB, SNR, SFDR, THD without identifiers
legend_str = {[‘ENOB: ‘, num2str(ENOB), ‘ bits’], [‘SNR: ‘, num2str(SNR), ‘ dB’], …
[‘SFDR: ‘, num2str(SFDR), ‘ dB’], [‘THD: ‘, num2str(THD), ‘ dB’]};
legend(legend_str, ‘Location’, ‘best’, ‘AutoUpdate’, ‘off’); % AutoUpdate off to prevent adding previous legend entries
% Display results
disp([‘Estimated Signal Tone Frequency: ‘, num2str(f_signal / 1e6), ‘ MHz’]);
disp([‘ENOB: ‘, num2str(ENOB), ‘ bits’]);
disp([‘SNR: ‘, num2str(SNR), ‘ dB’]);
disp([‘SFDR: ‘, num2str(SFDR), ‘ dB’]);
disp([‘THD: ‘, num2str(THD), ‘ dB’]);I have this code, the plot looks correct but the values don’t come out right. I even tested an ideal sine wave, but it’s the same. which means the code is wrong, but I can’t figure out which part of the code is wrong. it looks correct to me. please help me out;
% Parameters
N = 8192; % Number of samples for FFT
fs = 10e9; % Sampling frequency (10 GHz)
harmonics = 3; % Number of harmonics to consider
% Extract 8192 samples from OUTPUT (assuming OUTPUT is already defined)
x = OUTPUT(1:N);
% Normalize data to unit magnitude
x = x / max(abs(x));
% Perform FFT
X = fft(x);
% Frequency axis
f_axis = (0:N-1) * fs / N; % Frequency axis from 0 to fs
% Remove DC component
X(1) = 0;
% Find dominant frequency component
[~, max_idx] = max(abs(X)); % Find the index of the maximum magnitude
% Calculate estimated signal frequency
f_signal = f_axis(max_idx); % Frequency corresponding to the maximum magnitude
% Calculate SNR correctly
signal_power = abs(X(max_idx))^2; % Power of the signal tone
noise_power = sum(abs(X).^2) – signal_power; % Total noise power (excluding signal tone)
SNR = 10*log10(signal_power / noise_power); % Signal-to-Noise Ratio in dB
% Calculate ENOB
ENOB = (SNR – 1.76) / 6.02;
% Calculate SFDR
SFDR_power = max(abs(X))^2; % Power of the largest spurious component (excluding DC)
SFDR = 10*log10(SFDR_power / signal_power); % Spurious Free Dynamic Range in dB
% Calculate THD correctly
THD_power = sum(abs(X(2:end)).^2); % Total harmonic distortion power (excluding signal and DC)
THD = 10*log10(THD_power / signal_power); % Total harmonic distortion in dB
% Plot FFT magnitude spectrum (folded, centered around fs/2)
figure;
plot(f_axis / 1e6, 20*log10(abs(X) / N)); % Plot in MHz and dB
xlabel(‘Frequency (MHz)’);
ylabel(‘Magnitude (dB/Hz)’);
title(‘FFT Magnitude Spectrum’);
grid on;
xlim([0 fs/2/1e6]); % Limit x-axis to 0 to fs/2 in MHz
% Mark signal tone and harmonics on the plot
hold on;
plot(f_signal / 1e6, 20*log10(abs(X(max_idx)) / N), ‘ro’, ‘MarkerSize’, 10, ‘LineWidth’, 2); % Mark signal tone
for i = 1:harmonics
harmonic_freq = i * f_signal;
[~, harmonic_bin] = min(abs(f_axis – harmonic_freq)); % Find nearest bin index
plot(f_axis(harmonic_bin) / 1e6, 20*log10(abs(X(harmonic_bin)) / N), ‘go’, ‘MarkerSize’, 10, ‘LineWidth’, 2); % Mark harmonics
end
hold off;
% Create legend for ENOB, SNR, SFDR, THD without identifiers
legend_str = {[‘ENOB: ‘, num2str(ENOB), ‘ bits’], [‘SNR: ‘, num2str(SNR), ‘ dB’], …
[‘SFDR: ‘, num2str(SFDR), ‘ dB’], [‘THD: ‘, num2str(THD), ‘ dB’]};
legend(legend_str, ‘Location’, ‘best’, ‘AutoUpdate’, ‘off’); % AutoUpdate off to prevent adding previous legend entries
% Display results
disp([‘Estimated Signal Tone Frequency: ‘, num2str(f_signal / 1e6), ‘ MHz’]);
disp([‘ENOB: ‘, num2str(ENOB), ‘ bits’]);
disp([‘SNR: ‘, num2str(SNR), ‘ dB’]);
disp([‘SFDR: ‘, num2str(SFDR), ‘ dB’]);
disp([‘THD: ‘, num2str(THD), ‘ dB’]); I have this code, the plot looks correct but the values don’t come out right. I even tested an ideal sine wave, but it’s the same. which means the code is wrong, but I can’t figure out which part of the code is wrong. it looks correct to me. please help me out;
% Parameters
N = 8192; % Number of samples for FFT
fs = 10e9; % Sampling frequency (10 GHz)
harmonics = 3; % Number of harmonics to consider
% Extract 8192 samples from OUTPUT (assuming OUTPUT is already defined)
x = OUTPUT(1:N);
% Normalize data to unit magnitude
x = x / max(abs(x));
% Perform FFT
X = fft(x);
% Frequency axis
f_axis = (0:N-1) * fs / N; % Frequency axis from 0 to fs
% Remove DC component
X(1) = 0;
% Find dominant frequency component
[~, max_idx] = max(abs(X)); % Find the index of the maximum magnitude
% Calculate estimated signal frequency
f_signal = f_axis(max_idx); % Frequency corresponding to the maximum magnitude
% Calculate SNR correctly
signal_power = abs(X(max_idx))^2; % Power of the signal tone
noise_power = sum(abs(X).^2) – signal_power; % Total noise power (excluding signal tone)
SNR = 10*log10(signal_power / noise_power); % Signal-to-Noise Ratio in dB
% Calculate ENOB
ENOB = (SNR – 1.76) / 6.02;
% Calculate SFDR
SFDR_power = max(abs(X))^2; % Power of the largest spurious component (excluding DC)
SFDR = 10*log10(SFDR_power / signal_power); % Spurious Free Dynamic Range in dB
% Calculate THD correctly
THD_power = sum(abs(X(2:end)).^2); % Total harmonic distortion power (excluding signal and DC)
THD = 10*log10(THD_power / signal_power); % Total harmonic distortion in dB
% Plot FFT magnitude spectrum (folded, centered around fs/2)
figure;
plot(f_axis / 1e6, 20*log10(abs(X) / N)); % Plot in MHz and dB
xlabel(‘Frequency (MHz)’);
ylabel(‘Magnitude (dB/Hz)’);
title(‘FFT Magnitude Spectrum’);
grid on;
xlim([0 fs/2/1e6]); % Limit x-axis to 0 to fs/2 in MHz
% Mark signal tone and harmonics on the plot
hold on;
plot(f_signal / 1e6, 20*log10(abs(X(max_idx)) / N), ‘ro’, ‘MarkerSize’, 10, ‘LineWidth’, 2); % Mark signal tone
for i = 1:harmonics
harmonic_freq = i * f_signal;
[~, harmonic_bin] = min(abs(f_axis – harmonic_freq)); % Find nearest bin index
plot(f_axis(harmonic_bin) / 1e6, 20*log10(abs(X(harmonic_bin)) / N), ‘go’, ‘MarkerSize’, 10, ‘LineWidth’, 2); % Mark harmonics
end
hold off;
% Create legend for ENOB, SNR, SFDR, THD without identifiers
legend_str = {[‘ENOB: ‘, num2str(ENOB), ‘ bits’], [‘SNR: ‘, num2str(SNR), ‘ dB’], …
[‘SFDR: ‘, num2str(SFDR), ‘ dB’], [‘THD: ‘, num2str(THD), ‘ dB’]};
legend(legend_str, ‘Location’, ‘best’, ‘AutoUpdate’, ‘off’); % AutoUpdate off to prevent adding previous legend entries
% Display results
disp([‘Estimated Signal Tone Frequency: ‘, num2str(f_signal / 1e6), ‘ MHz’]);
disp([‘ENOB: ‘, num2str(ENOB), ‘ bits’]);
disp([‘SNR: ‘, num2str(SNR), ‘ dB’]);
disp([‘SFDR: ‘, num2str(SFDR), ‘ dB’]);
disp([‘THD: ‘, num2str(THD), ‘ dB’]); fft code, adc, dsp, snr, enoub, sfdr, thd MATLAB Answers — New Questions
Why is str2num not recommended when it is faster in certain circumstances?
I have a cell array of millions of strings representing dates with the format "yyyyMMddHHmmss"
I need to convert these to datetimes. After many attempts of various kinds I think I have found an optimal solution.
However, my solution requires that I use str2num instead of str2double and results in nearly 100x increase in speed. This is depite the fact that MATLAB recommends using str2double for "faster performance" and specifically discourages str2num.
In particular, str2double cannot convert a char array and results in Inf, while str2num converts the char array without issue.
Below is an example script.
(P.S. not directly related to this question, but if there is a faster way to convert cell arrays of strings to datetimes, let me know!)
%Make example input data
t1 = datetime(2000,1,1,0,0,0);
t2 = datetime("now");
t = string(datestr(t1:days(1):t2,’yyyymmddHHMMss’));
t_cell = cellstr(t); %<— This is the "cell array" example data
%Option 1: datetime cell array of strings
% —> Very slow (~0.75 s)
tic
tcheck1 = datetime(t_cell,’InputFormat’,’yyyyMMddHHmmss’);
toc
%Option 2: str2double
% —> DOES NOT WORK (results in Inf)
tic
da = char(t_cell);
year1 = str2double(da(:,1:4));
month1 = str2double(da(:,5:6));
day1 = str2double(da(:,7:8));
hour1 = str2double(da(:,9:10));
min1 = str2double(da(:,11:12));
sec1 = str2double(da(:,13:14));
tcheck2 = datetime(year1,month1,day1,hour1,min1,sec1);
toc
%Option 3: str2double with extra conversion from char to string
% —> About twice as fast as Option #1 (~0.4 s)
tic
da = char(t_cell);
year1 = str2double(string(da(:,1:4)));
month1 = str2double(string(da(:,5:6)));
day1 = str2double(string(da(:,7:8)));
hour1 = str2double(string(da(:,9:10)));
min1 = str2double(string(da(:,11:12)));
sec1 = str2double(string(da(:,13:14)));
tcheck3 = datetime(year1,month1,day1,hour1,min1,sec1);
toc
%Option 3: str2num
% —> About 100 times faster than Option #1 and #3 (~0.005 s)
tic
da = char(t_cell);
year1 = str2num(da(:,1:4));
month1 = str2num(da(:,5:6));
day1 = str2num(da(:,7:8));
hour1 = str2num(da(:,9:10));
min1 = str2num(da(:,11:12));
sec1 = str2num(da(:,13:14));
tcheck4 = datetime(year1,month1,day1,hour1,min1,sec1);
tocI have a cell array of millions of strings representing dates with the format "yyyyMMddHHmmss"
I need to convert these to datetimes. After many attempts of various kinds I think I have found an optimal solution.
However, my solution requires that I use str2num instead of str2double and results in nearly 100x increase in speed. This is depite the fact that MATLAB recommends using str2double for "faster performance" and specifically discourages str2num.
In particular, str2double cannot convert a char array and results in Inf, while str2num converts the char array without issue.
Below is an example script.
(P.S. not directly related to this question, but if there is a faster way to convert cell arrays of strings to datetimes, let me know!)
%Make example input data
t1 = datetime(2000,1,1,0,0,0);
t2 = datetime("now");
t = string(datestr(t1:days(1):t2,’yyyymmddHHMMss’));
t_cell = cellstr(t); %<— This is the "cell array" example data
%Option 1: datetime cell array of strings
% —> Very slow (~0.75 s)
tic
tcheck1 = datetime(t_cell,’InputFormat’,’yyyyMMddHHmmss’);
toc
%Option 2: str2double
% —> DOES NOT WORK (results in Inf)
tic
da = char(t_cell);
year1 = str2double(da(:,1:4));
month1 = str2double(da(:,5:6));
day1 = str2double(da(:,7:8));
hour1 = str2double(da(:,9:10));
min1 = str2double(da(:,11:12));
sec1 = str2double(da(:,13:14));
tcheck2 = datetime(year1,month1,day1,hour1,min1,sec1);
toc
%Option 3: str2double with extra conversion from char to string
% —> About twice as fast as Option #1 (~0.4 s)
tic
da = char(t_cell);
year1 = str2double(string(da(:,1:4)));
month1 = str2double(string(da(:,5:6)));
day1 = str2double(string(da(:,7:8)));
hour1 = str2double(string(da(:,9:10)));
min1 = str2double(string(da(:,11:12)));
sec1 = str2double(string(da(:,13:14)));
tcheck3 = datetime(year1,month1,day1,hour1,min1,sec1);
toc
%Option 3: str2num
% —> About 100 times faster than Option #1 and #3 (~0.005 s)
tic
da = char(t_cell);
year1 = str2num(da(:,1:4));
month1 = str2num(da(:,5:6));
day1 = str2num(da(:,7:8));
hour1 = str2num(da(:,9:10));
min1 = str2num(da(:,11:12));
sec1 = str2num(da(:,13:14));
tcheck4 = datetime(year1,month1,day1,hour1,min1,sec1);
toc I have a cell array of millions of strings representing dates with the format "yyyyMMddHHmmss"
I need to convert these to datetimes. After many attempts of various kinds I think I have found an optimal solution.
However, my solution requires that I use str2num instead of str2double and results in nearly 100x increase in speed. This is depite the fact that MATLAB recommends using str2double for "faster performance" and specifically discourages str2num.
In particular, str2double cannot convert a char array and results in Inf, while str2num converts the char array without issue.
Below is an example script.
(P.S. not directly related to this question, but if there is a faster way to convert cell arrays of strings to datetimes, let me know!)
%Make example input data
t1 = datetime(2000,1,1,0,0,0);
t2 = datetime("now");
t = string(datestr(t1:days(1):t2,’yyyymmddHHMMss’));
t_cell = cellstr(t); %<— This is the "cell array" example data
%Option 1: datetime cell array of strings
% —> Very slow (~0.75 s)
tic
tcheck1 = datetime(t_cell,’InputFormat’,’yyyyMMddHHmmss’);
toc
%Option 2: str2double
% —> DOES NOT WORK (results in Inf)
tic
da = char(t_cell);
year1 = str2double(da(:,1:4));
month1 = str2double(da(:,5:6));
day1 = str2double(da(:,7:8));
hour1 = str2double(da(:,9:10));
min1 = str2double(da(:,11:12));
sec1 = str2double(da(:,13:14));
tcheck2 = datetime(year1,month1,day1,hour1,min1,sec1);
toc
%Option 3: str2double with extra conversion from char to string
% —> About twice as fast as Option #1 (~0.4 s)
tic
da = char(t_cell);
year1 = str2double(string(da(:,1:4)));
month1 = str2double(string(da(:,5:6)));
day1 = str2double(string(da(:,7:8)));
hour1 = str2double(string(da(:,9:10)));
min1 = str2double(string(da(:,11:12)));
sec1 = str2double(string(da(:,13:14)));
tcheck3 = datetime(year1,month1,day1,hour1,min1,sec1);
toc
%Option 3: str2num
% —> About 100 times faster than Option #1 and #3 (~0.005 s)
tic
da = char(t_cell);
year1 = str2num(da(:,1:4));
month1 = str2num(da(:,5:6));
day1 = str2num(da(:,7:8));
hour1 = str2num(da(:,9:10));
min1 = str2num(da(:,11:12));
sec1 = str2num(da(:,13:14));
tcheck4 = datetime(year1,month1,day1,hour1,min1,sec1);
toc datetime, string, double, convert MATLAB Answers — New Questions
How do I synchronize PTP clocks between two Speedgoat target computers?
Can you give me an example for clock synchronization between two Speedgoat target computers using PTP?Can you give me an example for clock synchronization between two Speedgoat target computers using PTP? Can you give me an example for clock synchronization between two Speedgoat target computers using PTP? slrt, ptp, speedgoat, sync MATLAB Answers — New Questions
Retrieving Arrays Within Set of Matrices
Hello,
I have several sets of data that I want to plot on one graph. The problem is that each data set is in its own matrix. For instance, I have a 36×4 matrix (let’s call it M). In each of the cells in the 4th column is a 516×2 matrix, corresponding to x and y values. The x values are the same for each of the 516×2 matricies, so I just want to plot the y values against one set of x values. I try to make an additional matrix (let’s call it N) to have the y values all side by side by using the following code
N=[M{:,4}(:,2)]
But then I get the following error
Intermediate brace ‘{}’ indexing produced a comma-separated list with 36 values, but it must produce a single value when followed by subsequent indexing operations.
The end goal is to be able to use this after iterative peak fitting across multiple similar data sets, but I need to be able to efficiently visualize the resulting plots. I would be grateful for any help on this. Thank you!Hello,
I have several sets of data that I want to plot on one graph. The problem is that each data set is in its own matrix. For instance, I have a 36×4 matrix (let’s call it M). In each of the cells in the 4th column is a 516×2 matrix, corresponding to x and y values. The x values are the same for each of the 516×2 matricies, so I just want to plot the y values against one set of x values. I try to make an additional matrix (let’s call it N) to have the y values all side by side by using the following code
N=[M{:,4}(:,2)]
But then I get the following error
Intermediate brace ‘{}’ indexing produced a comma-separated list with 36 values, but it must produce a single value when followed by subsequent indexing operations.
The end goal is to be able to use this after iterative peak fitting across multiple similar data sets, but I need to be able to efficiently visualize the resulting plots. I would be grateful for any help on this. Thank you! Hello,
I have several sets of data that I want to plot on one graph. The problem is that each data set is in its own matrix. For instance, I have a 36×4 matrix (let’s call it M). In each of the cells in the 4th column is a 516×2 matrix, corresponding to x and y values. The x values are the same for each of the 516×2 matricies, so I just want to plot the y values against one set of x values. I try to make an additional matrix (let’s call it N) to have the y values all side by side by using the following code
N=[M{:,4}(:,2)]
But then I get the following error
Intermediate brace ‘{}’ indexing produced a comma-separated list with 36 values, but it must produce a single value when followed by subsequent indexing operations.
The end goal is to be able to use this after iterative peak fitting across multiple similar data sets, but I need to be able to efficiently visualize the resulting plots. I would be grateful for any help on this. Thank you! matrix MATLAB Answers — New Questions
How to create a 3D world and simulate a virtual camera in MATLAB on MacOS?
Hello,
I need to create a 3D world given a 3D model (STL, OBJ, etc.) and simulate a virtual camera in MATLAB.
The goal is to create a synthetic dataset where it contains image frames from the virtual camera inside the scene. The user would provide the intrinsics and the poses for the virtual camera.
I’m currently researching if MATLAB has this capability and I have found the following:
https://www.mathworks.com/help/driving/ref/simulation3dcamera.html
I think this would work well except that Simulink 3D is not supported on Mac, so I don’t have this option.
I have found the following link below which is very similar to what I need, but I’m having some trouble finding options to specify camera intrinsics to the view. It’s possible to provide intrinsics in a view?
https://www.mathworks.com/help/matlab/creating_plots/example-moving-the-camera-through-a-scene.html
Does anyone has any other ideas?
Thank you!Hello,
I need to create a 3D world given a 3D model (STL, OBJ, etc.) and simulate a virtual camera in MATLAB.
The goal is to create a synthetic dataset where it contains image frames from the virtual camera inside the scene. The user would provide the intrinsics and the poses for the virtual camera.
I’m currently researching if MATLAB has this capability and I have found the following:
https://www.mathworks.com/help/driving/ref/simulation3dcamera.html
I think this would work well except that Simulink 3D is not supported on Mac, so I don’t have this option.
I have found the following link below which is very similar to what I need, but I’m having some trouble finding options to specify camera intrinsics to the view. It’s possible to provide intrinsics in a view?
https://www.mathworks.com/help/matlab/creating_plots/example-moving-the-camera-through-a-scene.html
Does anyone has any other ideas?
Thank you! Hello,
I need to create a 3D world given a 3D model (STL, OBJ, etc.) and simulate a virtual camera in MATLAB.
The goal is to create a synthetic dataset where it contains image frames from the virtual camera inside the scene. The user would provide the intrinsics and the poses for the virtual camera.
I’m currently researching if MATLAB has this capability and I have found the following:
https://www.mathworks.com/help/driving/ref/simulation3dcamera.html
I think this would work well except that Simulink 3D is not supported on Mac, so I don’t have this option.
I have found the following link below which is very similar to what I need, but I’m having some trouble finding options to specify camera intrinsics to the view. It’s possible to provide intrinsics in a view?
https://www.mathworks.com/help/matlab/creating_plots/example-moving-the-camera-through-a-scene.html
Does anyone has any other ideas?
Thank you! image, camera, 3d, views MATLAB Answers — New Questions
SimMechanics Link Problem
I am trying to import a Solidowrks assembly into simMechanics. I followed all the steps as in the web site. I have the pull-down menu SinMechanics Link in SolidWorks. When I try to save the assembly in the xml format, I get this error:
Could not start MATLAB. Check your MATLAB installation. Consult documentation to identify possible causes of failure.
I get this error regarding Matlab is open or not.
Note: I am using Matlab 2010a and SolidWorks 2010I am trying to import a Solidowrks assembly into simMechanics. I followed all the steps as in the web site. I have the pull-down menu SinMechanics Link in SolidWorks. When I try to save the assembly in the xml format, I get this error:
Could not start MATLAB. Check your MATLAB installation. Consult documentation to identify possible causes of failure.
I get this error regarding Matlab is open or not.
Note: I am using Matlab 2010a and SolidWorks 2010 I am trying to import a Solidowrks assembly into simMechanics. I followed all the steps as in the web site. I have the pull-down menu SinMechanics Link in SolidWorks. When I try to save the assembly in the xml format, I get this error:
Could not start MATLAB. Check your MATLAB installation. Consult documentation to identify possible causes of failure.
I get this error regarding Matlab is open or not.
Note: I am using Matlab 2010a and SolidWorks 2010 solidworks, r2010a MATLAB Answers — New Questions
Is there a way to disable this?
I don’t manipulate my figures any, so I don’t need whatever toolbar this is. Also, it’s causing MATLAB to generate strange errors, which are annoying but don’t actually mean anything important for my program. I’m looking for a way to generate static figures (figures that cannot be panned, zoomed, etc) or at least disabling this toolbar when creating your normal bar graphs.I don’t manipulate my figures any, so I don’t need whatever toolbar this is. Also, it’s causing MATLAB to generate strange errors, which are annoying but don’t actually mean anything important for my program. I’m looking for a way to generate static figures (figures that cannot be panned, zoomed, etc) or at least disabling this toolbar when creating your normal bar graphs. I don’t manipulate my figures any, so I don’t need whatever toolbar this is. Also, it’s causing MATLAB to generate strange errors, which are annoying but don’t actually mean anything important for my program. I’m looking for a way to generate static figures (figures that cannot be panned, zoomed, etc) or at least disabling this toolbar when creating your normal bar graphs. matlab, figure MATLAB Answers — New Questions
lsqcurvefit not working properly
Hi all, I have multiple sets of data that are to be fitted by my fitting function. Since these data sets are kind of related, what I did was to use an inital guess to find the parameter values for the first dataset, and then use the parameter values as the guess for the second dataset so on and forth. However, the fitting was really bad. May I ask if there is another way around this kind of problem involving fitting of multiple datasets?
tic
%% Preparation
clear; clc
data = importdata("Experimental dataTransient AbsorptionFCPIB-293K-2.5mW-400nm-Jan072021 -ibg -bg -chirp.csv"); % insert file path within parenthesis
%% Preamble
% Fundamental constants
h = 4.0135667696*10^-15; % units: eV/ Hz
c = 3*10^8; % SI units
kB = 8.617333268*10^-5; % units: eV/ K
% Data
wavelength = data(1:end, 1); % contains all of the wavelengths
delay_t = data(1, 1:end); % conatains all of the delay times
E = (h*c)./(wavelength*10^-9); % contains all of the probe energies
% Range of data needed
Range_E = E>=1.5 & E<=2.2;
Range_W = wavelength >= (h*c)/(2.2*10^-9) & wavelength <= (h*c)/(1.5*10^-9);
Range_T = delay_t>=0.5 & delay_t<=1000;
E_p = E(Range_E); % probe energies for scatterplot
w_p = wavelength(Range_W);
delay_T = delay_t(Range_T);
Range_Efit = E_p>=1.62 & E_p<=max(E_p);
Range_Wfit = w_p >= (h*c)/(2.2*10^-9) & w_p <= (h*c)/(1.62*10^-9);
E_fit = E_p(Range_Efit); % probe energies for fitting
W_fit = w_p(Range_Wfit);
t_min = min(delay_T);
t_max = max(delay_T);
w_min = min(w_p);
w_max = max(w_p);
[row1, col1] = find(data == w_min);
[row2, col2] = find(data == w_max);
[row3, col3] = find(data == t_min);
[row4, col4] = find(data == t_max);
% New cleaned up data
data_new = data(row1:row2, col3:col4);% new data containing required delta A
% for n = 1:length(delay_T)
% delta_Abs(:,n) = -1*data_new(:,n);
% delta_Abs_norm(:,n) = delta_Abs(:,n)/max(delta_Abs(:,n));
% delta_Abs_fit(:,n) = data_new(Range_Wfit,n);
% delta_Abs_norm_fit(:,n) = delta_Abs_fit(:,n)/max(delta_Abs_fit(:, n));
% % plot command
% plot(E_p, delta_Abs_norm)
% xlabel(‘Probe Energy (eV)’)
% ylabel(‘Normalised Delta A (a.u.)’)
% legend(‘Experimental Data’)
% end
% Fitting function: Maxwell-Boltzmann distribution
function F = MB(y, e_fit)
data = importdata("Experimental dataTransient AbsorptionFCPIB-293K-2.5mW-400nm-Jan072021 -ibg -bg -chirp.csv");
h = 4.0135667696*10^-15;
c = 3*10^8;
kB = 8.617333268*10^-5;
delay_t = data(1, :);
Range_T = delay_t>=0.5 & delay_t<=1000;
delay_T = delay_t(Range_T);
wavelength = data(1:end, 1);
E = (h*c)./(wavelength*10^-9);
Range_E = E>=1.5 & E<=2.2;
E_p = E(Range_E);
Range_Efit = E_p>=1.62 & E_p<=max(E_p);
E_fit = E_p(Range_Efit);
for i = 1:length(E_fit)
E_fit = e_fit(i);
F(i) = y(1).*exp(-(E_fit./(kB.*y(2)))) + y(3);
end
F = F(:);
end
% For loop to create required datasets for plotting
for n = 2:length(delay_T)
delta_Abs(:,1) = -1*data_new(:,1);
delta_Abs_norm(:,1) = delta_Abs(:,1)./max(abs(delta_Abs(:,1)));
delta_Abs_fit(:,1) = data_new(Range_Wfit,1);
delta_Abs_norm_fit(:,1) = delta_Abs_norm(Range_Wfit);
delta_Abs(:,n) = -1*data_new(:,n);
delta_Abs_norm(:,n) = delta_Abs(:,n)./max(abs(delta_Abs(:,n)));
delta_Abs_fit(:,n) = data_new(Range_Wfit,n);
delta_Abs_norm_fit(:,n) = delta_Abs_norm(Range_Wfit);
% lsqcurvefit
optim_lsq = optimoptions(‘lsqcurvefit’, ‘Algorithm’, ‘levenberg-marquardt’, ‘MaxFunctionEvaluations’,10^20, ‘MaxIterations’, 10^20, ‘FunctionTolerance’,10^-20, ‘StepTolerance’, 10^-20);
lb = [0, 293, -1]; ub = [Inf, 6000, 1];
lb1 = [0, 293, -1]; ub1 = [Inf, 2000, 1];
lb2 = [0, 293, -1]; ub2 = [Inf, 1200, 1];
lb3 = [0, 293, -1]; ub3 = [Inf, 1000, 1];
lb4 = [0, 293, -1]; ub4 = [Inf, 750, 1];
y1 = [2*10^7, 1000, 0.5];
y2 = [2*10^7, 800, 0.5];
y3 = [2*10^10, 800, 0.5];
y4 = [2*10^11, 600, 0.5];
y5 = [2*10^14, 600, 0.5];
y(1,:) = lsqcurvefit(@MB, y1, E_fit, delta_Abs_norm_fit(:, 1), lb1, ub1, optim_lsq);
y(n,:) = lsqcurvefit(@MB, y(n-1, :), E_fit, delta_Abs_norm_fit(:, n), lb, ub, optim_lsq);
% plot command
plot(E_p, delta_Abs_norm)
hold on
plot(E_fit, MB(y(1,:), E_fit), ‘red’)
plot(E_fit, MB(y(n,:), E_fit), ‘red’)
xlabel(‘Probe Energy (eV)’)
ylabel(‘Normalised Delta A (a.u.)’)
legend(‘Fitted curve’)
end
carrier_T = y(:,2);
disp(carrier_T)
toc
%% Miscellaneous
% For a rectangular pic:
% drag horizontally until it just covers the letter ‘c’ in the word ‘col’
% For a square pic:
% drag horizontall until it just covers the letter ‘o’ in the word ‘Contribution’ in the next line)
% legend(‘Experimental Data’, ‘Fitted Curve’, ‘Carrier Contribution’,’Excitonic Contribution’)Hi all, I have multiple sets of data that are to be fitted by my fitting function. Since these data sets are kind of related, what I did was to use an inital guess to find the parameter values for the first dataset, and then use the parameter values as the guess for the second dataset so on and forth. However, the fitting was really bad. May I ask if there is another way around this kind of problem involving fitting of multiple datasets?
tic
%% Preparation
clear; clc
data = importdata("Experimental dataTransient AbsorptionFCPIB-293K-2.5mW-400nm-Jan072021 -ibg -bg -chirp.csv"); % insert file path within parenthesis
%% Preamble
% Fundamental constants
h = 4.0135667696*10^-15; % units: eV/ Hz
c = 3*10^8; % SI units
kB = 8.617333268*10^-5; % units: eV/ K
% Data
wavelength = data(1:end, 1); % contains all of the wavelengths
delay_t = data(1, 1:end); % conatains all of the delay times
E = (h*c)./(wavelength*10^-9); % contains all of the probe energies
% Range of data needed
Range_E = E>=1.5 & E<=2.2;
Range_W = wavelength >= (h*c)/(2.2*10^-9) & wavelength <= (h*c)/(1.5*10^-9);
Range_T = delay_t>=0.5 & delay_t<=1000;
E_p = E(Range_E); % probe energies for scatterplot
w_p = wavelength(Range_W);
delay_T = delay_t(Range_T);
Range_Efit = E_p>=1.62 & E_p<=max(E_p);
Range_Wfit = w_p >= (h*c)/(2.2*10^-9) & w_p <= (h*c)/(1.62*10^-9);
E_fit = E_p(Range_Efit); % probe energies for fitting
W_fit = w_p(Range_Wfit);
t_min = min(delay_T);
t_max = max(delay_T);
w_min = min(w_p);
w_max = max(w_p);
[row1, col1] = find(data == w_min);
[row2, col2] = find(data == w_max);
[row3, col3] = find(data == t_min);
[row4, col4] = find(data == t_max);
% New cleaned up data
data_new = data(row1:row2, col3:col4);% new data containing required delta A
% for n = 1:length(delay_T)
% delta_Abs(:,n) = -1*data_new(:,n);
% delta_Abs_norm(:,n) = delta_Abs(:,n)/max(delta_Abs(:,n));
% delta_Abs_fit(:,n) = data_new(Range_Wfit,n);
% delta_Abs_norm_fit(:,n) = delta_Abs_fit(:,n)/max(delta_Abs_fit(:, n));
% % plot command
% plot(E_p, delta_Abs_norm)
% xlabel(‘Probe Energy (eV)’)
% ylabel(‘Normalised Delta A (a.u.)’)
% legend(‘Experimental Data’)
% end
% Fitting function: Maxwell-Boltzmann distribution
function F = MB(y, e_fit)
data = importdata("Experimental dataTransient AbsorptionFCPIB-293K-2.5mW-400nm-Jan072021 -ibg -bg -chirp.csv");
h = 4.0135667696*10^-15;
c = 3*10^8;
kB = 8.617333268*10^-5;
delay_t = data(1, :);
Range_T = delay_t>=0.5 & delay_t<=1000;
delay_T = delay_t(Range_T);
wavelength = data(1:end, 1);
E = (h*c)./(wavelength*10^-9);
Range_E = E>=1.5 & E<=2.2;
E_p = E(Range_E);
Range_Efit = E_p>=1.62 & E_p<=max(E_p);
E_fit = E_p(Range_Efit);
for i = 1:length(E_fit)
E_fit = e_fit(i);
F(i) = y(1).*exp(-(E_fit./(kB.*y(2)))) + y(3);
end
F = F(:);
end
% For loop to create required datasets for plotting
for n = 2:length(delay_T)
delta_Abs(:,1) = -1*data_new(:,1);
delta_Abs_norm(:,1) = delta_Abs(:,1)./max(abs(delta_Abs(:,1)));
delta_Abs_fit(:,1) = data_new(Range_Wfit,1);
delta_Abs_norm_fit(:,1) = delta_Abs_norm(Range_Wfit);
delta_Abs(:,n) = -1*data_new(:,n);
delta_Abs_norm(:,n) = delta_Abs(:,n)./max(abs(delta_Abs(:,n)));
delta_Abs_fit(:,n) = data_new(Range_Wfit,n);
delta_Abs_norm_fit(:,n) = delta_Abs_norm(Range_Wfit);
% lsqcurvefit
optim_lsq = optimoptions(‘lsqcurvefit’, ‘Algorithm’, ‘levenberg-marquardt’, ‘MaxFunctionEvaluations’,10^20, ‘MaxIterations’, 10^20, ‘FunctionTolerance’,10^-20, ‘StepTolerance’, 10^-20);
lb = [0, 293, -1]; ub = [Inf, 6000, 1];
lb1 = [0, 293, -1]; ub1 = [Inf, 2000, 1];
lb2 = [0, 293, -1]; ub2 = [Inf, 1200, 1];
lb3 = [0, 293, -1]; ub3 = [Inf, 1000, 1];
lb4 = [0, 293, -1]; ub4 = [Inf, 750, 1];
y1 = [2*10^7, 1000, 0.5];
y2 = [2*10^7, 800, 0.5];
y3 = [2*10^10, 800, 0.5];
y4 = [2*10^11, 600, 0.5];
y5 = [2*10^14, 600, 0.5];
y(1,:) = lsqcurvefit(@MB, y1, E_fit, delta_Abs_norm_fit(:, 1), lb1, ub1, optim_lsq);
y(n,:) = lsqcurvefit(@MB, y(n-1, :), E_fit, delta_Abs_norm_fit(:, n), lb, ub, optim_lsq);
% plot command
plot(E_p, delta_Abs_norm)
hold on
plot(E_fit, MB(y(1,:), E_fit), ‘red’)
plot(E_fit, MB(y(n,:), E_fit), ‘red’)
xlabel(‘Probe Energy (eV)’)
ylabel(‘Normalised Delta A (a.u.)’)
legend(‘Fitted curve’)
end
carrier_T = y(:,2);
disp(carrier_T)
toc
%% Miscellaneous
% For a rectangular pic:
% drag horizontally until it just covers the letter ‘c’ in the word ‘col’
% For a square pic:
% drag horizontall until it just covers the letter ‘o’ in the word ‘Contribution’ in the next line)
% legend(‘Experimental Data’, ‘Fitted Curve’, ‘Carrier Contribution’,’Excitonic Contribution’) Hi all, I have multiple sets of data that are to be fitted by my fitting function. Since these data sets are kind of related, what I did was to use an inital guess to find the parameter values for the first dataset, and then use the parameter values as the guess for the second dataset so on and forth. However, the fitting was really bad. May I ask if there is another way around this kind of problem involving fitting of multiple datasets?
tic
%% Preparation
clear; clc
data = importdata("Experimental dataTransient AbsorptionFCPIB-293K-2.5mW-400nm-Jan072021 -ibg -bg -chirp.csv"); % insert file path within parenthesis
%% Preamble
% Fundamental constants
h = 4.0135667696*10^-15; % units: eV/ Hz
c = 3*10^8; % SI units
kB = 8.617333268*10^-5; % units: eV/ K
% Data
wavelength = data(1:end, 1); % contains all of the wavelengths
delay_t = data(1, 1:end); % conatains all of the delay times
E = (h*c)./(wavelength*10^-9); % contains all of the probe energies
% Range of data needed
Range_E = E>=1.5 & E<=2.2;
Range_W = wavelength >= (h*c)/(2.2*10^-9) & wavelength <= (h*c)/(1.5*10^-9);
Range_T = delay_t>=0.5 & delay_t<=1000;
E_p = E(Range_E); % probe energies for scatterplot
w_p = wavelength(Range_W);
delay_T = delay_t(Range_T);
Range_Efit = E_p>=1.62 & E_p<=max(E_p);
Range_Wfit = w_p >= (h*c)/(2.2*10^-9) & w_p <= (h*c)/(1.62*10^-9);
E_fit = E_p(Range_Efit); % probe energies for fitting
W_fit = w_p(Range_Wfit);
t_min = min(delay_T);
t_max = max(delay_T);
w_min = min(w_p);
w_max = max(w_p);
[row1, col1] = find(data == w_min);
[row2, col2] = find(data == w_max);
[row3, col3] = find(data == t_min);
[row4, col4] = find(data == t_max);
% New cleaned up data
data_new = data(row1:row2, col3:col4);% new data containing required delta A
% for n = 1:length(delay_T)
% delta_Abs(:,n) = -1*data_new(:,n);
% delta_Abs_norm(:,n) = delta_Abs(:,n)/max(delta_Abs(:,n));
% delta_Abs_fit(:,n) = data_new(Range_Wfit,n);
% delta_Abs_norm_fit(:,n) = delta_Abs_fit(:,n)/max(delta_Abs_fit(:, n));
% % plot command
% plot(E_p, delta_Abs_norm)
% xlabel(‘Probe Energy (eV)’)
% ylabel(‘Normalised Delta A (a.u.)’)
% legend(‘Experimental Data’)
% end
% Fitting function: Maxwell-Boltzmann distribution
function F = MB(y, e_fit)
data = importdata("Experimental dataTransient AbsorptionFCPIB-293K-2.5mW-400nm-Jan072021 -ibg -bg -chirp.csv");
h = 4.0135667696*10^-15;
c = 3*10^8;
kB = 8.617333268*10^-5;
delay_t = data(1, :);
Range_T = delay_t>=0.5 & delay_t<=1000;
delay_T = delay_t(Range_T);
wavelength = data(1:end, 1);
E = (h*c)./(wavelength*10^-9);
Range_E = E>=1.5 & E<=2.2;
E_p = E(Range_E);
Range_Efit = E_p>=1.62 & E_p<=max(E_p);
E_fit = E_p(Range_Efit);
for i = 1:length(E_fit)
E_fit = e_fit(i);
F(i) = y(1).*exp(-(E_fit./(kB.*y(2)))) + y(3);
end
F = F(:);
end
% For loop to create required datasets for plotting
for n = 2:length(delay_T)
delta_Abs(:,1) = -1*data_new(:,1);
delta_Abs_norm(:,1) = delta_Abs(:,1)./max(abs(delta_Abs(:,1)));
delta_Abs_fit(:,1) = data_new(Range_Wfit,1);
delta_Abs_norm_fit(:,1) = delta_Abs_norm(Range_Wfit);
delta_Abs(:,n) = -1*data_new(:,n);
delta_Abs_norm(:,n) = delta_Abs(:,n)./max(abs(delta_Abs(:,n)));
delta_Abs_fit(:,n) = data_new(Range_Wfit,n);
delta_Abs_norm_fit(:,n) = delta_Abs_norm(Range_Wfit);
% lsqcurvefit
optim_lsq = optimoptions(‘lsqcurvefit’, ‘Algorithm’, ‘levenberg-marquardt’, ‘MaxFunctionEvaluations’,10^20, ‘MaxIterations’, 10^20, ‘FunctionTolerance’,10^-20, ‘StepTolerance’, 10^-20);
lb = [0, 293, -1]; ub = [Inf, 6000, 1];
lb1 = [0, 293, -1]; ub1 = [Inf, 2000, 1];
lb2 = [0, 293, -1]; ub2 = [Inf, 1200, 1];
lb3 = [0, 293, -1]; ub3 = [Inf, 1000, 1];
lb4 = [0, 293, -1]; ub4 = [Inf, 750, 1];
y1 = [2*10^7, 1000, 0.5];
y2 = [2*10^7, 800, 0.5];
y3 = [2*10^10, 800, 0.5];
y4 = [2*10^11, 600, 0.5];
y5 = [2*10^14, 600, 0.5];
y(1,:) = lsqcurvefit(@MB, y1, E_fit, delta_Abs_norm_fit(:, 1), lb1, ub1, optim_lsq);
y(n,:) = lsqcurvefit(@MB, y(n-1, :), E_fit, delta_Abs_norm_fit(:, n), lb, ub, optim_lsq);
% plot command
plot(E_p, delta_Abs_norm)
hold on
plot(E_fit, MB(y(1,:), E_fit), ‘red’)
plot(E_fit, MB(y(n,:), E_fit), ‘red’)
xlabel(‘Probe Energy (eV)’)
ylabel(‘Normalised Delta A (a.u.)’)
legend(‘Fitted curve’)
end
carrier_T = y(:,2);
disp(carrier_T)
toc
%% Miscellaneous
% For a rectangular pic:
% drag horizontally until it just covers the letter ‘c’ in the word ‘col’
% For a square pic:
% drag horizontall until it just covers the letter ‘o’ in the word ‘Contribution’ in the next line)
% legend(‘Experimental Data’, ‘Fitted Curve’, ‘Carrier Contribution’,’Excitonic Contribution’) lsqcurvefit MATLAB Answers — New Questions
f = x^2024. Write a loop to find how many times f needs to be differentiated to get a result of zero.
A sequence of functions F0, F1, F2…is defined as follows, for x a positive real number:#
F0 = x^2024
For n>=1, the function Fn is the derivative of F(n-1), with respect to x.
Find the first value of n for which Fn = 0A sequence of functions F0, F1, F2…is defined as follows, for x a positive real number:#
F0 = x^2024
For n>=1, the function Fn is the derivative of F(n-1), with respect to x.
Find the first value of n for which Fn = 0 A sequence of functions F0, F1, F2…is defined as follows, for x a positive real number:#
F0 = x^2024
For n>=1, the function Fn is the derivative of F(n-1), with respect to x.
Find the first value of n for which Fn = 0 loops, differentiation MATLAB Answers — New Questions
Rename the indices of a vector in a certain way.
Hi all,
My code below has a vector and its index vector . It goes throguh the elements of and when it finds a zero element, it removes its index from the orginal index vector.
My problem here is: suppose the updated index vector is . How can I rename this vector so it increases in an acending order? For example: the first element in the updated index vector is , I want this to be , the second element in the updated index vector is , I want this to become , and so on so forth.
%define the index vector
idx = [1 2 3 4 5];
%define the vector
A = [5 0 6 0 3];
%initialise the vector that has all indices of zero elements
zero_indices = [];
%go through the elements of vector A
for uu = 1:numel(A)
%if the element is zero
if A(uu)==0
%assign its index to the zero-elements index vector
zeroindex = uu;
%collect all results from iterations
zero_indices = [zero_indices ; zeroindex];
end
end
%update the original index vector by removing the indicies that correspond
%to zero elements
idx(zero_indices) = [];
%rename the indices os that they beocome 1, 2, 3, …
Any help would be appreicted.
Thanks.Hi all,
My code below has a vector and its index vector . It goes throguh the elements of and when it finds a zero element, it removes its index from the orginal index vector.
My problem here is: suppose the updated index vector is . How can I rename this vector so it increases in an acending order? For example: the first element in the updated index vector is , I want this to be , the second element in the updated index vector is , I want this to become , and so on so forth.
%define the index vector
idx = [1 2 3 4 5];
%define the vector
A = [5 0 6 0 3];
%initialise the vector that has all indices of zero elements
zero_indices = [];
%go through the elements of vector A
for uu = 1:numel(A)
%if the element is zero
if A(uu)==0
%assign its index to the zero-elements index vector
zeroindex = uu;
%collect all results from iterations
zero_indices = [zero_indices ; zeroindex];
end
end
%update the original index vector by removing the indicies that correspond
%to zero elements
idx(zero_indices) = [];
%rename the indices os that they beocome 1, 2, 3, …
Any help would be appreicted.
Thanks. Hi all,
My code below has a vector and its index vector . It goes throguh the elements of and when it finds a zero element, it removes its index from the orginal index vector.
My problem here is: suppose the updated index vector is . How can I rename this vector so it increases in an acending order? For example: the first element in the updated index vector is , I want this to be , the second element in the updated index vector is , I want this to become , and so on so forth.
%define the index vector
idx = [1 2 3 4 5];
%define the vector
A = [5 0 6 0 3];
%initialise the vector that has all indices of zero elements
zero_indices = [];
%go through the elements of vector A
for uu = 1:numel(A)
%if the element is zero
if A(uu)==0
%assign its index to the zero-elements index vector
zeroindex = uu;
%collect all results from iterations
zero_indices = [zero_indices ; zeroindex];
end
end
%update the original index vector by removing the indicies that correspond
%to zero elements
idx(zero_indices) = [];
%rename the indices os that they beocome 1, 2, 3, …
Any help would be appreicted.
Thanks. index, matlab coder, vector, while loop, remove, delete MATLAB Answers — New Questions
How can I change the axis intervals using powers?
Hi.
I recently was trying to make a scientific graph, which required the X Axis to be in even intervals of powers of 10 (i.e. 0.1, 10, 100, 1000, etc.) with no in-betweeners. When I tried to use the xtick function, the command worked, but it didn’t create the necessary even spacing required at the intervals. What can I do? (The code and images are below.)
size = particle_size.("Size (d.nm)");
number = particle_size.("Number (Percent)");
plot(normalize(size,’range’,[0.1 10000]),number,"red",LineWidth=0.5)
xlim([0.1 10000])
ylim([0 14])
title("Particle Size Of Carbon Leaves",FontSize=20,FontWeight="bold")
xlabel("Size (d.nm)",FontSize=14,FontWeight="bold")
ylabel("Number (Percent)",FontSize=14,FontWeight="bold")
legend("Carbon Leaves",FontWeight="bold")
xtick = [0.1, 1, 10, 100, 1000, 10000];
box on
ax = gca;
ax.LineWidth = 2;
ax.FontSize = 12;
ax.XTick = xtick;
(The graph required)
(What MATLAB gave me)Hi.
I recently was trying to make a scientific graph, which required the X Axis to be in even intervals of powers of 10 (i.e. 0.1, 10, 100, 1000, etc.) with no in-betweeners. When I tried to use the xtick function, the command worked, but it didn’t create the necessary even spacing required at the intervals. What can I do? (The code and images are below.)
size = particle_size.("Size (d.nm)");
number = particle_size.("Number (Percent)");
plot(normalize(size,’range’,[0.1 10000]),number,"red",LineWidth=0.5)
xlim([0.1 10000])
ylim([0 14])
title("Particle Size Of Carbon Leaves",FontSize=20,FontWeight="bold")
xlabel("Size (d.nm)",FontSize=14,FontWeight="bold")
ylabel("Number (Percent)",FontSize=14,FontWeight="bold")
legend("Carbon Leaves",FontWeight="bold")
xtick = [0.1, 1, 10, 100, 1000, 10000];
box on
ax = gca;
ax.LineWidth = 2;
ax.FontSize = 12;
ax.XTick = xtick;
(The graph required)
(What MATLAB gave me) Hi.
I recently was trying to make a scientific graph, which required the X Axis to be in even intervals of powers of 10 (i.e. 0.1, 10, 100, 1000, etc.) with no in-betweeners. When I tried to use the xtick function, the command worked, but it didn’t create the necessary even spacing required at the intervals. What can I do? (The code and images are below.)
size = particle_size.("Size (d.nm)");
number = particle_size.("Number (Percent)");
plot(normalize(size,’range’,[0.1 10000]),number,"red",LineWidth=0.5)
xlim([0.1 10000])
ylim([0 14])
title("Particle Size Of Carbon Leaves",FontSize=20,FontWeight="bold")
xlabel("Size (d.nm)",FontSize=14,FontWeight="bold")
ylabel("Number (Percent)",FontSize=14,FontWeight="bold")
legend("Carbon Leaves",FontWeight="bold")
xtick = [0.1, 1, 10, 100, 1000, 10000];
box on
ax = gca;
ax.LineWidth = 2;
ax.FontSize = 12;
ax.XTick = xtick;
(The graph required)
(What MATLAB gave me) graphs, axis MATLAB Answers — New Questions
Contact angle measurements for droplets with a capillary
Hello everyone
My name is Baraa, I recently started using Matlab (Bigginner), and I need your help in explaining the error I keep making in the following code. The code is supposed to measure the contact angle of a droplet based on defining the edges of the droplet, masking the capillary, dividing the pixels on the edges of the droplet by 2 (so we can have left and right), finding the reflection of each side to define the contact points between the surface and the droplet on each side, and finally connecting the contact points together. The code then fits the pixels to find the tangent and calculates the contact angle between the tangent and the line between the contact points.
The main problem is that the code doesn’t work with all droplets and most of the time I have errors with droplets with high wettability and high volume (the droplets spread on the surface). The error message is as follows:
Index in position 1 exceeds array bounds. Index must not exceed 1113.
Error in findreflection (line 50)
x2=trace(index+n2:index+n-1,2);
Error in contactAngleImageAnalysis (line 104)
[x0L,y0L,indexL]=findreflection([edgeL.x,edgeL.y],70,0); % change the last entry (160) to zero and see what happens
How can I modify the code to make it suitable for any droplet volume?
P.S
The code always fails to read this image (Co-Eth-1, see attached) and it reads probably reads this image (Co-Eth-1b, see attached). Please refer to the two images.
Thank you very much in advance
clc
clear all
close all
addpath(genpath("C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopcodesContact Angle FittingScriptsSubpixel Matlab v2.11"));
addpath(genpath("C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopcodesContact Angle FittingScripts"));
main_path = "C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopIMAGES25.06.24";
output_folder = "C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopsessileDrop_processed";
%these are the coordinates of the polygon to mask the cannula
Xright=3100;%this the X value on the right side of the ploygon and it represents top and bottom if the right side of the polygon.
Xleft=2800;%this is the X value of the left side of the ploygon and it represents both top and bottom x cordinates
Y_top=0;% this is the y value on the top side of the polygon for both left and right side
Y_bottom=2050;% this is the y value of the bottom side of the ploygon for both left and right side
%******************************pixel intensity***************************
pixelValue=255;
%***********************threshold to be used*****************************
trsh_sub=4;
% Read a group of images from a folder
imageFiles = dir(fullfile(main_path, ‘*.png’)); % Assuming images are in PNG format
numImages = input(‘Enter the number of images to work with: ‘);
% Create cell arrays to store data
imageNumbers = zeros(numImages, 1);
CAL_values = zeros(numImages, 1);
CAR_values = zeros(numImages, 1);
for k = 1:numImages
% Load image
filename = imageFiles(k).name;
im_load = fullfile(main_path, filename);
im = imread(im_load);
%—————————————————————–
% Masking the cannula
%—————————————————————–
% Define the coordinates of the four points
maskSize = size(im);
pointCoordinates = [Xleft, Y_bottom; Xright, Y_bottom; Xright, Y_top; Xleft, Y_top];
mask = zeros(maskSize(1), maskSize(2));
mask = poly2mask(pointCoordinates(:, 1), pointCoordinates(:, 2), maskSize(1), maskSize(2));
burnedImage = im;
burnedImage(mask) = pixelValue;
%—————————————————————
% Step 2 Detect boundaries in image
%—————————————————————
[edges, RI] = subpixelEdges(burnedImage, trsh_sub);
im_size=size(burnedImage);
im_size=size(burnedImage);
points = detectHarrisFeatures(burnedImage);
strongest = selectStrongest(points,10);
f2h=figure;
imshow(burnedImage)
hold on
plot(edges.x,edges.y,’r.’,’LineWidth’,2)
% plot(edges.x(1), edges.y(1),’b*’)
% plot(edges.x(im_size(1)),edges.y(im_size(2)),’g*’)
plot(strongest)
set(f2h,’Units’,’normalized’,’Position’,[0.31,0.6,0.3,0.3])
%—————————————————————
% Step 3 Select longes boundary in image
%—————————————————————
longestedge=findlongestedge(edges,size(burnedImage),5);
f3h=figure;
imshow(burnedImage)
hold on
plot(longestedge.x,longestedge.y,’r.’,’LineWidth’,2)
set(f3h,’Units’,’normalized’,’Position’,[0.62,0.6,0.3,0.3])
%—————————————————————
% Step 4 Split edge into left and right and sort it
%—————————————————————
[edgeL,edgeR]=leftrightedges(longestedge);
f4h=figure;
imshow(burnedImage)
hold on
plot(edgeL.x,edgeL.y,’r’,’LineWidth’,2)
plot(edgeR.x,edgeR.y,’b’,’LineWidth’,2)
set(f4h,’Units’,’normalized’,’Position’,[0.0,0.3,0.3,0.3])
%—————————————————————
% Step 5 Find reflection
%—————————————————————
[x0L,y0L,indexL]=findreflection([edgeL.x,edgeL.y],70,0); % change the last entry (160) to zero and see what happens
[x0R,y0R,indexR]=findreflection([edgeR.x,edgeR.y],60,0);
f5h=figure;
imshow(burnedImage)
hold on
plot(edgeL.x,edgeL.y,’r’,’LineWidth’,2)
plot(edgeR.x,edgeR.y,’b’,’LineWidth’,2)
plot(x0L,y0L,’yx’,’MarkerSize’,10,’LineWidth’,2)
plot(x0R,y0R,’yx’,’MarkerSize’,10,’LineWidth’,2)
t=linspace(-3,3);
plot((x0L-x0R)*t+x0R,(y0L-y0R)*t+y0R,’r–‘,’LineWidth’,2)
set(f5h,’Units’,’normalized’,’Position’,[0.31,0.3,0.3,0.3])
%—————————————————————
% Step 6 Fit data to polynomial
%—————————————————————
PolyData=polynomialfit(edgeL,edgeR,[x0L,y0L],[x0R,y0R]);
f6h=figure;
imshow(burnedImage)
hold on
t=linspace(-3,3);
plot((x0L-x0R)*t+x0R,(y0L-y0R)*t+y0R,’r–‘,’LineWidth’,2)
plot(PolyData.EvalPolyL(:,1),PolyData.EvalPolyL(:,2),’r’,’LineWidth’,2)
plot(PolyData.EvalPolyR(:,1),PolyData.EvalPolyR(:,2),’b’,’LineWidth’,2)
radius=500;
tilt=atand((y0R-y0L)/(x0R-x0L));
plot([PolyData.TLL(1),PolyData.TLL(1)+radius*cosd(PolyData.CAL-tilt)],[PolyData.TLL(2),PolyData.TLL(2)-radius*sind(PolyData.CAL-tilt)],’LineWidth’, 2,’color’,’g’)
plot([PolyData.TLR(1),PolyData.TLR(1)-radius*cosd(PolyData.CAR+tilt)],[PolyData.TLR(2),PolyData.TLR(2)-radius*sind(PolyData.CAR+tilt)],’LineWidth’, 2,’color’,’g’)
legend([‘contact angles, CA left= ‘,num2str(PolyData.CAL),’ CA Right= ‘,num2str(PolyData.CAR)])
set(f6h,’Units’,’normalized’,’Position’,[0.62,0.3,0.3,0.3])
display([‘Polynomial fit return the contact angles, CA Left=’,num2str(PolyData.CAL),’ CA Right=’,num2str(PolyData.CAR)])
% % Store data in the table
imageNumbers(k) = k;
CAL_values(k) = PolyData.CAL;
CAR_values(k) = PolyData.CAR;
% Save processed image to a new folder
if ~exist(output_folder, ‘dir’)
mkdir(output_folder);
end
% Save processed image in the specified formats
[~, name, ext] = fileparts(filename);
processed_filename = [name ‘_processed’];
% Check if the filename already exists, if so, append a unique identifier
index = 1;
while exist(fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.jpg’]), ‘file’)
index = index + 1;
end
% Save as JPG
imwrite(burnedImage, fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.jpg’]));
% Save as FIG
saveas(f6h, fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.fig’]));
% Save result to TXT
nsave = fullfile(output_folder, [name, ‘_’, num2str(index), ‘.txt’]);
result_vary = rand(10); % Example data, replace with your actual data
save(nsave, ‘result_vary’, ‘-ASCII’);
disp([‘Processed image saved as: ‘, processed_filename]);
end
% Create table from cell arrays
tableData = table(imageNumbers, CAL_values, CAR_values);
% Save table to a text file
output_filename = fullfile(output_folder, ‘contactAngle_table_data.txt’);
writetable(tableData, output_filename, ‘Delimiter’, ‘t’);
disp([‘Table data saved as: ‘, output_filename]);
% Display the table
disp(tableData);Hello everyone
My name is Baraa, I recently started using Matlab (Bigginner), and I need your help in explaining the error I keep making in the following code. The code is supposed to measure the contact angle of a droplet based on defining the edges of the droplet, masking the capillary, dividing the pixels on the edges of the droplet by 2 (so we can have left and right), finding the reflection of each side to define the contact points between the surface and the droplet on each side, and finally connecting the contact points together. The code then fits the pixels to find the tangent and calculates the contact angle between the tangent and the line between the contact points.
The main problem is that the code doesn’t work with all droplets and most of the time I have errors with droplets with high wettability and high volume (the droplets spread on the surface). The error message is as follows:
Index in position 1 exceeds array bounds. Index must not exceed 1113.
Error in findreflection (line 50)
x2=trace(index+n2:index+n-1,2);
Error in contactAngleImageAnalysis (line 104)
[x0L,y0L,indexL]=findreflection([edgeL.x,edgeL.y],70,0); % change the last entry (160) to zero and see what happens
How can I modify the code to make it suitable for any droplet volume?
P.S
The code always fails to read this image (Co-Eth-1, see attached) and it reads probably reads this image (Co-Eth-1b, see attached). Please refer to the two images.
Thank you very much in advance
clc
clear all
close all
addpath(genpath("C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopcodesContact Angle FittingScriptsSubpixel Matlab v2.11"));
addpath(genpath("C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopcodesContact Angle FittingScripts"));
main_path = "C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopIMAGES25.06.24";
output_folder = "C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopsessileDrop_processed";
%these are the coordinates of the polygon to mask the cannula
Xright=3100;%this the X value on the right side of the ploygon and it represents top and bottom if the right side of the polygon.
Xleft=2800;%this is the X value of the left side of the ploygon and it represents both top and bottom x cordinates
Y_top=0;% this is the y value on the top side of the polygon for both left and right side
Y_bottom=2050;% this is the y value of the bottom side of the ploygon for both left and right side
%******************************pixel intensity***************************
pixelValue=255;
%***********************threshold to be used*****************************
trsh_sub=4;
% Read a group of images from a folder
imageFiles = dir(fullfile(main_path, ‘*.png’)); % Assuming images are in PNG format
numImages = input(‘Enter the number of images to work with: ‘);
% Create cell arrays to store data
imageNumbers = zeros(numImages, 1);
CAL_values = zeros(numImages, 1);
CAR_values = zeros(numImages, 1);
for k = 1:numImages
% Load image
filename = imageFiles(k).name;
im_load = fullfile(main_path, filename);
im = imread(im_load);
%—————————————————————–
% Masking the cannula
%—————————————————————–
% Define the coordinates of the four points
maskSize = size(im);
pointCoordinates = [Xleft, Y_bottom; Xright, Y_bottom; Xright, Y_top; Xleft, Y_top];
mask = zeros(maskSize(1), maskSize(2));
mask = poly2mask(pointCoordinates(:, 1), pointCoordinates(:, 2), maskSize(1), maskSize(2));
burnedImage = im;
burnedImage(mask) = pixelValue;
%—————————————————————
% Step 2 Detect boundaries in image
%—————————————————————
[edges, RI] = subpixelEdges(burnedImage, trsh_sub);
im_size=size(burnedImage);
im_size=size(burnedImage);
points = detectHarrisFeatures(burnedImage);
strongest = selectStrongest(points,10);
f2h=figure;
imshow(burnedImage)
hold on
plot(edges.x,edges.y,’r.’,’LineWidth’,2)
% plot(edges.x(1), edges.y(1),’b*’)
% plot(edges.x(im_size(1)),edges.y(im_size(2)),’g*’)
plot(strongest)
set(f2h,’Units’,’normalized’,’Position’,[0.31,0.6,0.3,0.3])
%—————————————————————
% Step 3 Select longes boundary in image
%—————————————————————
longestedge=findlongestedge(edges,size(burnedImage),5);
f3h=figure;
imshow(burnedImage)
hold on
plot(longestedge.x,longestedge.y,’r.’,’LineWidth’,2)
set(f3h,’Units’,’normalized’,’Position’,[0.62,0.6,0.3,0.3])
%—————————————————————
% Step 4 Split edge into left and right and sort it
%—————————————————————
[edgeL,edgeR]=leftrightedges(longestedge);
f4h=figure;
imshow(burnedImage)
hold on
plot(edgeL.x,edgeL.y,’r’,’LineWidth’,2)
plot(edgeR.x,edgeR.y,’b’,’LineWidth’,2)
set(f4h,’Units’,’normalized’,’Position’,[0.0,0.3,0.3,0.3])
%—————————————————————
% Step 5 Find reflection
%—————————————————————
[x0L,y0L,indexL]=findreflection([edgeL.x,edgeL.y],70,0); % change the last entry (160) to zero and see what happens
[x0R,y0R,indexR]=findreflection([edgeR.x,edgeR.y],60,0);
f5h=figure;
imshow(burnedImage)
hold on
plot(edgeL.x,edgeL.y,’r’,’LineWidth’,2)
plot(edgeR.x,edgeR.y,’b’,’LineWidth’,2)
plot(x0L,y0L,’yx’,’MarkerSize’,10,’LineWidth’,2)
plot(x0R,y0R,’yx’,’MarkerSize’,10,’LineWidth’,2)
t=linspace(-3,3);
plot((x0L-x0R)*t+x0R,(y0L-y0R)*t+y0R,’r–‘,’LineWidth’,2)
set(f5h,’Units’,’normalized’,’Position’,[0.31,0.3,0.3,0.3])
%—————————————————————
% Step 6 Fit data to polynomial
%—————————————————————
PolyData=polynomialfit(edgeL,edgeR,[x0L,y0L],[x0R,y0R]);
f6h=figure;
imshow(burnedImage)
hold on
t=linspace(-3,3);
plot((x0L-x0R)*t+x0R,(y0L-y0R)*t+y0R,’r–‘,’LineWidth’,2)
plot(PolyData.EvalPolyL(:,1),PolyData.EvalPolyL(:,2),’r’,’LineWidth’,2)
plot(PolyData.EvalPolyR(:,1),PolyData.EvalPolyR(:,2),’b’,’LineWidth’,2)
radius=500;
tilt=atand((y0R-y0L)/(x0R-x0L));
plot([PolyData.TLL(1),PolyData.TLL(1)+radius*cosd(PolyData.CAL-tilt)],[PolyData.TLL(2),PolyData.TLL(2)-radius*sind(PolyData.CAL-tilt)],’LineWidth’, 2,’color’,’g’)
plot([PolyData.TLR(1),PolyData.TLR(1)-radius*cosd(PolyData.CAR+tilt)],[PolyData.TLR(2),PolyData.TLR(2)-radius*sind(PolyData.CAR+tilt)],’LineWidth’, 2,’color’,’g’)
legend([‘contact angles, CA left= ‘,num2str(PolyData.CAL),’ CA Right= ‘,num2str(PolyData.CAR)])
set(f6h,’Units’,’normalized’,’Position’,[0.62,0.3,0.3,0.3])
display([‘Polynomial fit return the contact angles, CA Left=’,num2str(PolyData.CAL),’ CA Right=’,num2str(PolyData.CAR)])
% % Store data in the table
imageNumbers(k) = k;
CAL_values(k) = PolyData.CAL;
CAR_values(k) = PolyData.CAR;
% Save processed image to a new folder
if ~exist(output_folder, ‘dir’)
mkdir(output_folder);
end
% Save processed image in the specified formats
[~, name, ext] = fileparts(filename);
processed_filename = [name ‘_processed’];
% Check if the filename already exists, if so, append a unique identifier
index = 1;
while exist(fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.jpg’]), ‘file’)
index = index + 1;
end
% Save as JPG
imwrite(burnedImage, fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.jpg’]));
% Save as FIG
saveas(f6h, fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.fig’]));
% Save result to TXT
nsave = fullfile(output_folder, [name, ‘_’, num2str(index), ‘.txt’]);
result_vary = rand(10); % Example data, replace with your actual data
save(nsave, ‘result_vary’, ‘-ASCII’);
disp([‘Processed image saved as: ‘, processed_filename]);
end
% Create table from cell arrays
tableData = table(imageNumbers, CAL_values, CAR_values);
% Save table to a text file
output_filename = fullfile(output_folder, ‘contactAngle_table_data.txt’);
writetable(tableData, output_filename, ‘Delimiter’, ‘t’);
disp([‘Table data saved as: ‘, output_filename]);
% Display the table
disp(tableData); Hello everyone
My name is Baraa, I recently started using Matlab (Bigginner), and I need your help in explaining the error I keep making in the following code. The code is supposed to measure the contact angle of a droplet based on defining the edges of the droplet, masking the capillary, dividing the pixels on the edges of the droplet by 2 (so we can have left and right), finding the reflection of each side to define the contact points between the surface and the droplet on each side, and finally connecting the contact points together. The code then fits the pixels to find the tangent and calculates the contact angle between the tangent and the line between the contact points.
The main problem is that the code doesn’t work with all droplets and most of the time I have errors with droplets with high wettability and high volume (the droplets spread on the surface). The error message is as follows:
Index in position 1 exceeds array bounds. Index must not exceed 1113.
Error in findreflection (line 50)
x2=trace(index+n2:index+n-1,2);
Error in contactAngleImageAnalysis (line 104)
[x0L,y0L,indexL]=findreflection([edgeL.x,edgeL.y],70,0); % change the last entry (160) to zero and see what happens
How can I modify the code to make it suitable for any droplet volume?
P.S
The code always fails to read this image (Co-Eth-1, see attached) and it reads probably reads this image (Co-Eth-1b, see attached). Please refer to the two images.
Thank you very much in advance
clc
clear all
close all
addpath(genpath("C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopcodesContact Angle FittingScriptsSubpixel Matlab v2.11"));
addpath(genpath("C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopcodesContact Angle FittingScripts"));
main_path = "C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopIMAGES25.06.24";
output_folder = "C:UsersBara’a Al-khateebDesktopOthersStudentsGideon MensahLaptopsessileDrop_processed";
%these are the coordinates of the polygon to mask the cannula
Xright=3100;%this the X value on the right side of the ploygon and it represents top and bottom if the right side of the polygon.
Xleft=2800;%this is the X value of the left side of the ploygon and it represents both top and bottom x cordinates
Y_top=0;% this is the y value on the top side of the polygon for both left and right side
Y_bottom=2050;% this is the y value of the bottom side of the ploygon for both left and right side
%******************************pixel intensity***************************
pixelValue=255;
%***********************threshold to be used*****************************
trsh_sub=4;
% Read a group of images from a folder
imageFiles = dir(fullfile(main_path, ‘*.png’)); % Assuming images are in PNG format
numImages = input(‘Enter the number of images to work with: ‘);
% Create cell arrays to store data
imageNumbers = zeros(numImages, 1);
CAL_values = zeros(numImages, 1);
CAR_values = zeros(numImages, 1);
for k = 1:numImages
% Load image
filename = imageFiles(k).name;
im_load = fullfile(main_path, filename);
im = imread(im_load);
%—————————————————————–
% Masking the cannula
%—————————————————————–
% Define the coordinates of the four points
maskSize = size(im);
pointCoordinates = [Xleft, Y_bottom; Xright, Y_bottom; Xright, Y_top; Xleft, Y_top];
mask = zeros(maskSize(1), maskSize(2));
mask = poly2mask(pointCoordinates(:, 1), pointCoordinates(:, 2), maskSize(1), maskSize(2));
burnedImage = im;
burnedImage(mask) = pixelValue;
%—————————————————————
% Step 2 Detect boundaries in image
%—————————————————————
[edges, RI] = subpixelEdges(burnedImage, trsh_sub);
im_size=size(burnedImage);
im_size=size(burnedImage);
points = detectHarrisFeatures(burnedImage);
strongest = selectStrongest(points,10);
f2h=figure;
imshow(burnedImage)
hold on
plot(edges.x,edges.y,’r.’,’LineWidth’,2)
% plot(edges.x(1), edges.y(1),’b*’)
% plot(edges.x(im_size(1)),edges.y(im_size(2)),’g*’)
plot(strongest)
set(f2h,’Units’,’normalized’,’Position’,[0.31,0.6,0.3,0.3])
%—————————————————————
% Step 3 Select longes boundary in image
%—————————————————————
longestedge=findlongestedge(edges,size(burnedImage),5);
f3h=figure;
imshow(burnedImage)
hold on
plot(longestedge.x,longestedge.y,’r.’,’LineWidth’,2)
set(f3h,’Units’,’normalized’,’Position’,[0.62,0.6,0.3,0.3])
%—————————————————————
% Step 4 Split edge into left and right and sort it
%—————————————————————
[edgeL,edgeR]=leftrightedges(longestedge);
f4h=figure;
imshow(burnedImage)
hold on
plot(edgeL.x,edgeL.y,’r’,’LineWidth’,2)
plot(edgeR.x,edgeR.y,’b’,’LineWidth’,2)
set(f4h,’Units’,’normalized’,’Position’,[0.0,0.3,0.3,0.3])
%—————————————————————
% Step 5 Find reflection
%—————————————————————
[x0L,y0L,indexL]=findreflection([edgeL.x,edgeL.y],70,0); % change the last entry (160) to zero and see what happens
[x0R,y0R,indexR]=findreflection([edgeR.x,edgeR.y],60,0);
f5h=figure;
imshow(burnedImage)
hold on
plot(edgeL.x,edgeL.y,’r’,’LineWidth’,2)
plot(edgeR.x,edgeR.y,’b’,’LineWidth’,2)
plot(x0L,y0L,’yx’,’MarkerSize’,10,’LineWidth’,2)
plot(x0R,y0R,’yx’,’MarkerSize’,10,’LineWidth’,2)
t=linspace(-3,3);
plot((x0L-x0R)*t+x0R,(y0L-y0R)*t+y0R,’r–‘,’LineWidth’,2)
set(f5h,’Units’,’normalized’,’Position’,[0.31,0.3,0.3,0.3])
%—————————————————————
% Step 6 Fit data to polynomial
%—————————————————————
PolyData=polynomialfit(edgeL,edgeR,[x0L,y0L],[x0R,y0R]);
f6h=figure;
imshow(burnedImage)
hold on
t=linspace(-3,3);
plot((x0L-x0R)*t+x0R,(y0L-y0R)*t+y0R,’r–‘,’LineWidth’,2)
plot(PolyData.EvalPolyL(:,1),PolyData.EvalPolyL(:,2),’r’,’LineWidth’,2)
plot(PolyData.EvalPolyR(:,1),PolyData.EvalPolyR(:,2),’b’,’LineWidth’,2)
radius=500;
tilt=atand((y0R-y0L)/(x0R-x0L));
plot([PolyData.TLL(1),PolyData.TLL(1)+radius*cosd(PolyData.CAL-tilt)],[PolyData.TLL(2),PolyData.TLL(2)-radius*sind(PolyData.CAL-tilt)],’LineWidth’, 2,’color’,’g’)
plot([PolyData.TLR(1),PolyData.TLR(1)-radius*cosd(PolyData.CAR+tilt)],[PolyData.TLR(2),PolyData.TLR(2)-radius*sind(PolyData.CAR+tilt)],’LineWidth’, 2,’color’,’g’)
legend([‘contact angles, CA left= ‘,num2str(PolyData.CAL),’ CA Right= ‘,num2str(PolyData.CAR)])
set(f6h,’Units’,’normalized’,’Position’,[0.62,0.3,0.3,0.3])
display([‘Polynomial fit return the contact angles, CA Left=’,num2str(PolyData.CAL),’ CA Right=’,num2str(PolyData.CAR)])
% % Store data in the table
imageNumbers(k) = k;
CAL_values(k) = PolyData.CAL;
CAR_values(k) = PolyData.CAR;
% Save processed image to a new folder
if ~exist(output_folder, ‘dir’)
mkdir(output_folder);
end
% Save processed image in the specified formats
[~, name, ext] = fileparts(filename);
processed_filename = [name ‘_processed’];
% Check if the filename already exists, if so, append a unique identifier
index = 1;
while exist(fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.jpg’]), ‘file’)
index = index + 1;
end
% Save as JPG
imwrite(burnedImage, fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.jpg’]));
% Save as FIG
saveas(f6h, fullfile(output_folder, [processed_filename, ‘_’, num2str(index), ‘.fig’]));
% Save result to TXT
nsave = fullfile(output_folder, [name, ‘_’, num2str(index), ‘.txt’]);
result_vary = rand(10); % Example data, replace with your actual data
save(nsave, ‘result_vary’, ‘-ASCII’);
disp([‘Processed image saved as: ‘, processed_filename]);
end
% Create table from cell arrays
tableData = table(imageNumbers, CAL_values, CAR_values);
% Save table to a text file
output_filename = fullfile(output_folder, ‘contactAngle_table_data.txt’);
writetable(tableData, output_filename, ‘Delimiter’, ‘t’);
disp([‘Table data saved as: ‘, output_filename]);
% Display the table
disp(tableData); droplet, wettability, contact angle MATLAB Answers — New Questions
Unrecognized function or variable ‘asbQuadcopterStart’.
I got the same problem as another case followed:
Unrecognized function or variable ‘asbQuadcopterStart’. – MATLAB Answers – MATLAB Central (mathworks.com)
Error Msg: Unrecognized function or variable ‘asbQuadcopterStart’.
But I am sure that both
Aerospace Blockset
Aerospace Toolbox
are installed in my computer. Which can be both showed on the attached image.
So, Which step I missed?
Thanks a lot!I got the same problem as another case followed:
Unrecognized function or variable ‘asbQuadcopterStart’. – MATLAB Answers – MATLAB Central (mathworks.com)
Error Msg: Unrecognized function or variable ‘asbQuadcopterStart’.
But I am sure that both
Aerospace Blockset
Aerospace Toolbox
are installed in my computer. Which can be both showed on the attached image.
So, Which step I missed?
Thanks a lot! I got the same problem as another case followed:
Unrecognized function or variable ‘asbQuadcopterStart’. – MATLAB Answers – MATLAB Central (mathworks.com)
Error Msg: Unrecognized function or variable ‘asbQuadcopterStart’.
But I am sure that both
Aerospace Blockset
Aerospace Toolbox
are installed in my computer. Which can be both showed on the attached image.
So, Which step I missed?
Thanks a lot! asbquadcopterstart, aerospace MATLAB Answers — New Questions
How can I express all the variables Vcm1, Vcm2, Vcm3, Vcm4 in num2str without getting an error?
annotation(‘textbox’,dim,’String’,((num2str(Vcm1),num2str(Vcm2),num2str(Vcm3),num2str(Vcm4)), ‘FontSize’;15)annotation(‘textbox’,dim,’String’,((num2str(Vcm1),num2str(Vcm2),num2str(Vcm3),num2str(Vcm4)), ‘FontSize’;15) annotation(‘textbox’,dim,’String’,((num2str(Vcm1),num2str(Vcm2),num2str(Vcm3),num2str(Vcm4)), ‘FontSize’;15) num2str MATLAB Answers — New Questions
plotting Graph in 3D help
function basic
K=0.2; n=0.3; lam=0.1;
%Defining parameters
sol1 = bvpinit(linspace(0,6,300),[0 0 0 0 0]);
sol = bvp4c(@bvp2D, @bc2D, sol1);
x = sol.x;
y = sol.y;
%%% Plotting of the velocity
figure (1)
plot(x, y(2, 🙂 ,’linewidth’, 1.5);
hold on
xlabel(‘eta’, ‘fontweight’, ‘bold’, ‘fontsize’, 16)
ylabel(‘f^{prime}(eta)’, ‘fontweight’, ‘bold’, ‘fontsize’, 16)
%% Residual of the boundary conditions
function residual = bc2D(y0, yinf)
residual=[y0(1); y0(2) – 1; y0(4)+n*y0(3); yinf(2)-lam; yinf(4)];
end
%% System of First Order ODEs
function yvector = bvp2D(~,y)
yy1 =(1/(1+K))*(-y(1)*y(3)+y(2)^2-K*y(5)-lam^2);
yy2 =(2/(2+K))*(-y(1)*y(5)+y(2)*y(4)+K*(2*y(4)+y(3)));
yvector = [y(2);y(3);yy1; y(5); yy2];
end
end
i want to plot this graph in 3D, how can I?function basic
K=0.2; n=0.3; lam=0.1;
%Defining parameters
sol1 = bvpinit(linspace(0,6,300),[0 0 0 0 0]);
sol = bvp4c(@bvp2D, @bc2D, sol1);
x = sol.x;
y = sol.y;
%%% Plotting of the velocity
figure (1)
plot(x, y(2, 🙂 ,’linewidth’, 1.5);
hold on
xlabel(‘eta’, ‘fontweight’, ‘bold’, ‘fontsize’, 16)
ylabel(‘f^{prime}(eta)’, ‘fontweight’, ‘bold’, ‘fontsize’, 16)
%% Residual of the boundary conditions
function residual = bc2D(y0, yinf)
residual=[y0(1); y0(2) – 1; y0(4)+n*y0(3); yinf(2)-lam; yinf(4)];
end
%% System of First Order ODEs
function yvector = bvp2D(~,y)
yy1 =(1/(1+K))*(-y(1)*y(3)+y(2)^2-K*y(5)-lam^2);
yy2 =(2/(2+K))*(-y(1)*y(5)+y(2)*y(4)+K*(2*y(4)+y(3)));
yvector = [y(2);y(3);yy1; y(5); yy2];
end
end
i want to plot this graph in 3D, how can I? function basic
K=0.2; n=0.3; lam=0.1;
%Defining parameters
sol1 = bvpinit(linspace(0,6,300),[0 0 0 0 0]);
sol = bvp4c(@bvp2D, @bc2D, sol1);
x = sol.x;
y = sol.y;
%%% Plotting of the velocity
figure (1)
plot(x, y(2, 🙂 ,’linewidth’, 1.5);
hold on
xlabel(‘eta’, ‘fontweight’, ‘bold’, ‘fontsize’, 16)
ylabel(‘f^{prime}(eta)’, ‘fontweight’, ‘bold’, ‘fontsize’, 16)
%% Residual of the boundary conditions
function residual = bc2D(y0, yinf)
residual=[y0(1); y0(2) – 1; y0(4)+n*y0(3); yinf(2)-lam; yinf(4)];
end
%% System of First Order ODEs
function yvector = bvp2D(~,y)
yy1 =(1/(1+K))*(-y(1)*y(3)+y(2)^2-K*y(5)-lam^2);
yy2 =(2/(2+K))*(-y(1)*y(5)+y(2)*y(4)+K*(2*y(4)+y(3)));
yvector = [y(2);y(3);yy1; y(5); yy2];
end
end
i want to plot this graph in 3D, how can I? bvp4c, 2d plotting, 3d plotting MATLAB Answers — New Questions