Category: Matlab
Category Archives: Matlab
Optimization with non linear least square regression
In an optimisation problem I have 4 parameters to optimise. Once the algorithm converges, why does it assign the upper bound value to the first parameter, while assigning the lower bounds to the second and third?In an optimisation problem I have 4 parameters to optimise. Once the algorithm converges, why does it assign the upper bound value to the first parameter, while assigning the lower bounds to the second and third? In an optimisation problem I have 4 parameters to optimise. Once the algorithm converges, why does it assign the upper bound value to the first parameter, while assigning the lower bounds to the second and third? least square regression, lsqnonlin, curve fitting, optimization MATLAB Answers — New Questions
Matlab Compiler erroneously include YOLOv2-3-4 support packages in standaloneApp (even though I do not use them in my code) which results in 700+ MB EXE file
I recently installed these 3 support packages on my Windows 10 workstation (running Matlab R2023b Update 9 – latest AFAIK) :
Computer Vision Toolbox Model for YOLO v2 Object Detection
Computer Vision Toolbox Model for YOLO v3 Object Detection
Computer Vision Toolbox Model for YOLO v4 Object Detection
Since then, I noticed that when I build a standaloneApplication, the archive (EXE file) is enormous (700+ MB as compared to ~1.8MB beforehand)
So I decided to peek into the EXE archive (using 7-zip) to try to identify the file causing this and I realized that these where now included even though I do not use any YOLO detector in said App :
It looks like the dependency analyzer thinks I need them for some reason…
Is this a bug or else is there a setting somewhere I can use to exclude these support-packages from being included in my App ?
Thanks!
SébastienI recently installed these 3 support packages on my Windows 10 workstation (running Matlab R2023b Update 9 – latest AFAIK) :
Computer Vision Toolbox Model for YOLO v2 Object Detection
Computer Vision Toolbox Model for YOLO v3 Object Detection
Computer Vision Toolbox Model for YOLO v4 Object Detection
Since then, I noticed that when I build a standaloneApplication, the archive (EXE file) is enormous (700+ MB as compared to ~1.8MB beforehand)
So I decided to peek into the EXE archive (using 7-zip) to try to identify the file causing this and I realized that these where now included even though I do not use any YOLO detector in said App :
It looks like the dependency analyzer thinks I need them for some reason…
Is this a bug or else is there a setting somewhere I can use to exclude these support-packages from being included in my App ?
Thanks!
Sébastien I recently installed these 3 support packages on my Windows 10 workstation (running Matlab R2023b Update 9 – latest AFAIK) :
Computer Vision Toolbox Model for YOLO v2 Object Detection
Computer Vision Toolbox Model for YOLO v3 Object Detection
Computer Vision Toolbox Model for YOLO v4 Object Detection
Since then, I noticed that when I build a standaloneApplication, the archive (EXE file) is enormous (700+ MB as compared to ~1.8MB beforehand)
So I decided to peek into the EXE archive (using 7-zip) to try to identify the file causing this and I realized that these where now included even though I do not use any YOLO detector in said App :
It looks like the dependency analyzer thinks I need them for some reason…
Is this a bug or else is there a setting somewhere I can use to exclude these support-packages from being included in my App ?
Thanks!
Sébastien compiler, yolo, enormous executable, vision toolbox, support package MATLAB Answers — New Questions
Adding two columns together to create a new column of data
I am trying to add two columns of data together to create a new column, but I am receiving an error message and the data is not being added appropriately.
For example, I want to create something where I add the values of R and L to create Z:
R L Z
1 7 8
2 2 4
3 5 8
4 1 5
However when using a simple code like:
Z = R + L
We are receiving an error. I tried using the sum function, but it is simply adding all the vairables together, but not adding each row individually to create this variable Z that is a new column.I am trying to add two columns of data together to create a new column, but I am receiving an error message and the data is not being added appropriately.
For example, I want to create something where I add the values of R and L to create Z:
R L Z
1 7 8
2 2 4
3 5 8
4 1 5
However when using a simple code like:
Z = R + L
We are receiving an error. I tried using the sum function, but it is simply adding all the vairables together, but not adding each row individually to create this variable Z that is a new column. I am trying to add two columns of data together to create a new column, but I am receiving an error message and the data is not being added appropriately.
For example, I want to create something where I add the values of R and L to create Z:
R L Z
1 7 8
2 2 4
3 5 8
4 1 5
However when using a simple code like:
Z = R + L
We are receiving an error. I tried using the sum function, but it is simply adding all the vairables together, but not adding each row individually to create this variable Z that is a new column. columns, matrix array MATLAB Answers — New Questions
Initial condition from output of another Integrator block?
Hello, I want to know how can I get the end state from an integrator block and put it in as initial condition from another integrator block.
Both get the same initial condition , i want to get the end of the output value from the first integrator block as input for the second integrator block instead. I want to apply this for a in series-reactor set,so the output values from the first reactor are the input from the second.Thanks in advanceHello, I want to know how can I get the end state from an integrator block and put it in as initial condition from another integrator block.
Both get the same initial condition , i want to get the end of the output value from the first integrator block as input for the second integrator block instead. I want to apply this for a in series-reactor set,so the output values from the first reactor are the input from the second.Thanks in advance Hello, I want to know how can I get the end state from an integrator block and put it in as initial condition from another integrator block.
Both get the same initial condition , i want to get the end of the output value from the first integrator block as input for the second integrator block instead. I want to apply this for a in series-reactor set,so the output values from the first reactor are the input from the second.Thanks in advance simulink MATLAB Answers — New Questions
FRF – PSD Calculation Using Welch’s Method Producing Less Sharp Peaks for a Linear System
Hi,
I am attempting to compute the Frequency Response Function (FRF) of a linear system using Welch’s method for estimating the Power Spectral Density (PSD). However, the results I obtain lack the sharp peaks expected for a linear system, and I would like guidance on whether my code or approach is correct, or if I might be missing something fundamental.
Despite using these settings and varying the parameters, the FRF I compute does not show sharp peaks that I expect for a linear system. The peaks are relatively broad, which makes it difficult to identify resonant frequencies clearly. I am uncertain whether:
My choice of parameters (e.g., nfft,window_length,noverlapnfft, window_length, noverlapnfft,window_length,noverlap) is contributing to this issue.
There might be a problem in my preprocessing or interpretation of the data.
Please advise, thankyou!
Fs = 8192;
window_length = 3144;
noverlap = 0.75*window_length;
nfft = 2048;
FileName = ‘exp1_0’;
FileStart = 1;
FileEnd = 10;
fileDirectory = ‘D:xx’;
% Define the window function
window_function = hanning(window_length);
% Initialize accumulators for averaging
sum_Pxx = 0; % Sum of auto-power spectrum of voltage
sum_Pxy = 0; % Sum of cross-power spectrum
% Loop over all test files = averaging
for filenum = FileStart:FileEnd
% Load data from each file
fullFileName = [fileDirectory, FileName, sprintf(‘%02d’, filenum), ‘.mat’];
fileData = load(fullFileName);
% Extract Velocity and Voltage Data
velocity_data = fileData.([FileName, sprintf(‘%02d’, filenum)]).Y(4).Data; % Output: Velocity (m/s)
voltage_data = fileData.([FileName, sprintf(‘%02d’, filenum)]).Y(3).Data; % Input: Voltage (V)
% Compute PSDs using Welch’s method
[Pxx, f] = pwelch(voltage_data, window_function, noverlap, nfft, Fs); % Auto-power spectrum of voltage
[Pxy, ~] = cpsd(velocity_data, voltage_data, window_function, noverlap, nfft, Fs); % Cross-power spectrum
% Accumulate results for averaging
sum_Pxx = sum_Pxx + Pxx;
sum_Pxy = sum_Pxy + Pxy;
end
% Compute FRF (H = Pxy / Pxx)
H = sum_Pxy ./ sum_Pxx;
% Convert to dB
H_mag_dB = 20 * log10(abs(H));
% Apply smoothing and moving average
window_size = 5;
smoothed_H_w = smoothdata(H_mag_dB, ‘movmean’, window_size);
% Plot FRF
figure;
plot(f, smoothed_H_w , ‘r’);
hold on;
title([‘FRF of Random Test with – Window Length: ‘, num2str(window_length), …
‘, Overlap: ‘, num2str(noverlap), …
‘, nfft: ‘, num2str(nfft)]);
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude (dB)’);
grid on;
xlim([1 300]);
hold off;Hi,
I am attempting to compute the Frequency Response Function (FRF) of a linear system using Welch’s method for estimating the Power Spectral Density (PSD). However, the results I obtain lack the sharp peaks expected for a linear system, and I would like guidance on whether my code or approach is correct, or if I might be missing something fundamental.
Despite using these settings and varying the parameters, the FRF I compute does not show sharp peaks that I expect for a linear system. The peaks are relatively broad, which makes it difficult to identify resonant frequencies clearly. I am uncertain whether:
My choice of parameters (e.g., nfft,window_length,noverlapnfft, window_length, noverlapnfft,window_length,noverlap) is contributing to this issue.
There might be a problem in my preprocessing or interpretation of the data.
Please advise, thankyou!
Fs = 8192;
window_length = 3144;
noverlap = 0.75*window_length;
nfft = 2048;
FileName = ‘exp1_0’;
FileStart = 1;
FileEnd = 10;
fileDirectory = ‘D:xx’;
% Define the window function
window_function = hanning(window_length);
% Initialize accumulators for averaging
sum_Pxx = 0; % Sum of auto-power spectrum of voltage
sum_Pxy = 0; % Sum of cross-power spectrum
% Loop over all test files = averaging
for filenum = FileStart:FileEnd
% Load data from each file
fullFileName = [fileDirectory, FileName, sprintf(‘%02d’, filenum), ‘.mat’];
fileData = load(fullFileName);
% Extract Velocity and Voltage Data
velocity_data = fileData.([FileName, sprintf(‘%02d’, filenum)]).Y(4).Data; % Output: Velocity (m/s)
voltage_data = fileData.([FileName, sprintf(‘%02d’, filenum)]).Y(3).Data; % Input: Voltage (V)
% Compute PSDs using Welch’s method
[Pxx, f] = pwelch(voltage_data, window_function, noverlap, nfft, Fs); % Auto-power spectrum of voltage
[Pxy, ~] = cpsd(velocity_data, voltage_data, window_function, noverlap, nfft, Fs); % Cross-power spectrum
% Accumulate results for averaging
sum_Pxx = sum_Pxx + Pxx;
sum_Pxy = sum_Pxy + Pxy;
end
% Compute FRF (H = Pxy / Pxx)
H = sum_Pxy ./ sum_Pxx;
% Convert to dB
H_mag_dB = 20 * log10(abs(H));
% Apply smoothing and moving average
window_size = 5;
smoothed_H_w = smoothdata(H_mag_dB, ‘movmean’, window_size);
% Plot FRF
figure;
plot(f, smoothed_H_w , ‘r’);
hold on;
title([‘FRF of Random Test with – Window Length: ‘, num2str(window_length), …
‘, Overlap: ‘, num2str(noverlap), …
‘, nfft: ‘, num2str(nfft)]);
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude (dB)’);
grid on;
xlim([1 300]);
hold off; Hi,
I am attempting to compute the Frequency Response Function (FRF) of a linear system using Welch’s method for estimating the Power Spectral Density (PSD). However, the results I obtain lack the sharp peaks expected for a linear system, and I would like guidance on whether my code or approach is correct, or if I might be missing something fundamental.
Despite using these settings and varying the parameters, the FRF I compute does not show sharp peaks that I expect for a linear system. The peaks are relatively broad, which makes it difficult to identify resonant frequencies clearly. I am uncertain whether:
My choice of parameters (e.g., nfft,window_length,noverlapnfft, window_length, noverlapnfft,window_length,noverlap) is contributing to this issue.
There might be a problem in my preprocessing or interpretation of the data.
Please advise, thankyou!
Fs = 8192;
window_length = 3144;
noverlap = 0.75*window_length;
nfft = 2048;
FileName = ‘exp1_0’;
FileStart = 1;
FileEnd = 10;
fileDirectory = ‘D:xx’;
% Define the window function
window_function = hanning(window_length);
% Initialize accumulators for averaging
sum_Pxx = 0; % Sum of auto-power spectrum of voltage
sum_Pxy = 0; % Sum of cross-power spectrum
% Loop over all test files = averaging
for filenum = FileStart:FileEnd
% Load data from each file
fullFileName = [fileDirectory, FileName, sprintf(‘%02d’, filenum), ‘.mat’];
fileData = load(fullFileName);
% Extract Velocity and Voltage Data
velocity_data = fileData.([FileName, sprintf(‘%02d’, filenum)]).Y(4).Data; % Output: Velocity (m/s)
voltage_data = fileData.([FileName, sprintf(‘%02d’, filenum)]).Y(3).Data; % Input: Voltage (V)
% Compute PSDs using Welch’s method
[Pxx, f] = pwelch(voltage_data, window_function, noverlap, nfft, Fs); % Auto-power spectrum of voltage
[Pxy, ~] = cpsd(velocity_data, voltage_data, window_function, noverlap, nfft, Fs); % Cross-power spectrum
% Accumulate results for averaging
sum_Pxx = sum_Pxx + Pxx;
sum_Pxy = sum_Pxy + Pxy;
end
% Compute FRF (H = Pxy / Pxx)
H = sum_Pxy ./ sum_Pxx;
% Convert to dB
H_mag_dB = 20 * log10(abs(H));
% Apply smoothing and moving average
window_size = 5;
smoothed_H_w = smoothdata(H_mag_dB, ‘movmean’, window_size);
% Plot FRF
figure;
plot(f, smoothed_H_w , ‘r’);
hold on;
title([‘FRF of Random Test with – Window Length: ‘, num2str(window_length), …
‘, Overlap: ‘, num2str(noverlap), …
‘, nfft: ‘, num2str(nfft)]);
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude (dB)’);
grid on;
xlim([1 300]);
hold off; fft, psd MATLAB Answers — New Questions
Why do I get an error regarding third-party software when downloading or installing a support package?
When downloading or installing a support package I get an error regarding being unable to install third-party software.When downloading or installing a support package I get an error regarding being unable to install third-party software. When downloading or installing a support package I get an error regarding being unable to install third-party software. MATLAB Answers — New Questions
Question about training neural networks for regression problem using the Adam optimizer
Hello,
I am trying to construct and train a neural network to do a regression task for multi-output problem. However, I am starting with a toy problem with single output in order to understand how things work. I tried to use both functions ‘trainNetwork’ and ‘trainnet’ but both do not work as expected. In the toy problem, I am trying to approximate a simple function using the neural network with only 2 layers of 20 neuros per layer. The network does not converge for either of the functions above.
Could you tell me if I am doing something wrong in the way I am using them. Thank you
clear; clc; close all;
t = linspace(0,2*pi,500);
s = cos(2*pi*t).*exp(0.1*t) + sech(0.2*t);
%%
% Normalize inputs to the range [0, 1]
input_min = min(t); % Overall minimum
input_max = max(t); % Overall maximum
normalized_inputs = (t – input_min) / (input_max – input_min);
% Normalize outputs to the range [0, 1]
output_min = min(s); % Overall minimum
output_max = max(s); % Overall maximum
normalized_outputs = (s – output_min) / (output_max – output_min);
%%
% Define the architecture
layers = [
featureInputLayer(size(normalized_inputs, 1)) % Input layer
fullyConnectedLayer(20) % Hidden layer with 20 neurons
reluLayer % Activation function
fullyConnectedLayer(20) % Hidden layer with 20 neurons
reluLayer % Activation function
fullyConnectedLayer(size(normalized_outputs, 1)) % Output layer
regressionLayer % Regression layer for continuous outputs
];
idx = randperm(numel(t));
train_idx = idx(1:round(0.8*numel(t)));
val_idx = idx(round(0.8*numel(t))+1:end);
t_train = normalized_inputs(train_idx);
s_train = normalized_outputs(train_idx);
t_val = normalized_inputs(val_idx);
s_val = normalized_outputs(val_idx);
miniBatchSize = 32;
options = trainingOptions(‘adam’, …
‘MiniBatchSize’, miniBatchSize, …
‘MaxEpochs’, 2000, …
‘InitialLearnRate’, 0.001, …
‘LearnRateSchedule’, ‘piecewise’, …
‘LearnRateDropFactor’, 0.1, …
‘LearnRateDropPeriod’, 1000, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, {t_val’, s_val’}, …
‘ValidationFrequency’, 10, …
‘Plots’, ‘training-progress’, …
‘Verbose’, true);
% Train the network
% net = trainnet(normalized_inputs’, normalized_outputs’, layers, "mse", options);
net = trainNetwork(normalized_inputs’, normalized_outputs’, layers, options);
% net = fitrnet(normalized_inputs’, normalized_outputs’, ‘Activations’, "tanh" , …
% "LayerSizes",[50 50 50]);
% Predict using the trained network
normalized_predictions = predict(net, normalized_inputs’)’;
% De-standardize predictions
predictions = normalized_predictions .* (output_max – output_min) + output_min;
% Evaluate performance (e.g., Mean Squared Error)
mse_loss = mean((normalized_outputs – normalized_predictions).^2, ‘all’);
fprintf(‘MSE: %.4fn’, mse_loss);
%%
figure(‘units’,’normalized’,’outerposition’,[0 0 1 1])
plot(t,normalized_outputs,’r’);
grid;
hold on
plot(t,normalized_predictions,’–b’);
legend(‘Truth’,’NN’,’Location’,’best’);
set(gcf,’color’,’w’)Hello,
I am trying to construct and train a neural network to do a regression task for multi-output problem. However, I am starting with a toy problem with single output in order to understand how things work. I tried to use both functions ‘trainNetwork’ and ‘trainnet’ but both do not work as expected. In the toy problem, I am trying to approximate a simple function using the neural network with only 2 layers of 20 neuros per layer. The network does not converge for either of the functions above.
Could you tell me if I am doing something wrong in the way I am using them. Thank you
clear; clc; close all;
t = linspace(0,2*pi,500);
s = cos(2*pi*t).*exp(0.1*t) + sech(0.2*t);
%%
% Normalize inputs to the range [0, 1]
input_min = min(t); % Overall minimum
input_max = max(t); % Overall maximum
normalized_inputs = (t – input_min) / (input_max – input_min);
% Normalize outputs to the range [0, 1]
output_min = min(s); % Overall minimum
output_max = max(s); % Overall maximum
normalized_outputs = (s – output_min) / (output_max – output_min);
%%
% Define the architecture
layers = [
featureInputLayer(size(normalized_inputs, 1)) % Input layer
fullyConnectedLayer(20) % Hidden layer with 20 neurons
reluLayer % Activation function
fullyConnectedLayer(20) % Hidden layer with 20 neurons
reluLayer % Activation function
fullyConnectedLayer(size(normalized_outputs, 1)) % Output layer
regressionLayer % Regression layer for continuous outputs
];
idx = randperm(numel(t));
train_idx = idx(1:round(0.8*numel(t)));
val_idx = idx(round(0.8*numel(t))+1:end);
t_train = normalized_inputs(train_idx);
s_train = normalized_outputs(train_idx);
t_val = normalized_inputs(val_idx);
s_val = normalized_outputs(val_idx);
miniBatchSize = 32;
options = trainingOptions(‘adam’, …
‘MiniBatchSize’, miniBatchSize, …
‘MaxEpochs’, 2000, …
‘InitialLearnRate’, 0.001, …
‘LearnRateSchedule’, ‘piecewise’, …
‘LearnRateDropFactor’, 0.1, …
‘LearnRateDropPeriod’, 1000, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, {t_val’, s_val’}, …
‘ValidationFrequency’, 10, …
‘Plots’, ‘training-progress’, …
‘Verbose’, true);
% Train the network
% net = trainnet(normalized_inputs’, normalized_outputs’, layers, "mse", options);
net = trainNetwork(normalized_inputs’, normalized_outputs’, layers, options);
% net = fitrnet(normalized_inputs’, normalized_outputs’, ‘Activations’, "tanh" , …
% "LayerSizes",[50 50 50]);
% Predict using the trained network
normalized_predictions = predict(net, normalized_inputs’)’;
% De-standardize predictions
predictions = normalized_predictions .* (output_max – output_min) + output_min;
% Evaluate performance (e.g., Mean Squared Error)
mse_loss = mean((normalized_outputs – normalized_predictions).^2, ‘all’);
fprintf(‘MSE: %.4fn’, mse_loss);
%%
figure(‘units’,’normalized’,’outerposition’,[0 0 1 1])
plot(t,normalized_outputs,’r’);
grid;
hold on
plot(t,normalized_predictions,’–b’);
legend(‘Truth’,’NN’,’Location’,’best’);
set(gcf,’color’,’w’) Hello,
I am trying to construct and train a neural network to do a regression task for multi-output problem. However, I am starting with a toy problem with single output in order to understand how things work. I tried to use both functions ‘trainNetwork’ and ‘trainnet’ but both do not work as expected. In the toy problem, I am trying to approximate a simple function using the neural network with only 2 layers of 20 neuros per layer. The network does not converge for either of the functions above.
Could you tell me if I am doing something wrong in the way I am using them. Thank you
clear; clc; close all;
t = linspace(0,2*pi,500);
s = cos(2*pi*t).*exp(0.1*t) + sech(0.2*t);
%%
% Normalize inputs to the range [0, 1]
input_min = min(t); % Overall minimum
input_max = max(t); % Overall maximum
normalized_inputs = (t – input_min) / (input_max – input_min);
% Normalize outputs to the range [0, 1]
output_min = min(s); % Overall minimum
output_max = max(s); % Overall maximum
normalized_outputs = (s – output_min) / (output_max – output_min);
%%
% Define the architecture
layers = [
featureInputLayer(size(normalized_inputs, 1)) % Input layer
fullyConnectedLayer(20) % Hidden layer with 20 neurons
reluLayer % Activation function
fullyConnectedLayer(20) % Hidden layer with 20 neurons
reluLayer % Activation function
fullyConnectedLayer(size(normalized_outputs, 1)) % Output layer
regressionLayer % Regression layer for continuous outputs
];
idx = randperm(numel(t));
train_idx = idx(1:round(0.8*numel(t)));
val_idx = idx(round(0.8*numel(t))+1:end);
t_train = normalized_inputs(train_idx);
s_train = normalized_outputs(train_idx);
t_val = normalized_inputs(val_idx);
s_val = normalized_outputs(val_idx);
miniBatchSize = 32;
options = trainingOptions(‘adam’, …
‘MiniBatchSize’, miniBatchSize, …
‘MaxEpochs’, 2000, …
‘InitialLearnRate’, 0.001, …
‘LearnRateSchedule’, ‘piecewise’, …
‘LearnRateDropFactor’, 0.1, …
‘LearnRateDropPeriod’, 1000, …
‘Shuffle’, ‘every-epoch’, …
‘ValidationData’, {t_val’, s_val’}, …
‘ValidationFrequency’, 10, …
‘Plots’, ‘training-progress’, …
‘Verbose’, true);
% Train the network
% net = trainnet(normalized_inputs’, normalized_outputs’, layers, "mse", options);
net = trainNetwork(normalized_inputs’, normalized_outputs’, layers, options);
% net = fitrnet(normalized_inputs’, normalized_outputs’, ‘Activations’, "tanh" , …
% "LayerSizes",[50 50 50]);
% Predict using the trained network
normalized_predictions = predict(net, normalized_inputs’)’;
% De-standardize predictions
predictions = normalized_predictions .* (output_max – output_min) + output_min;
% Evaluate performance (e.g., Mean Squared Error)
mse_loss = mean((normalized_outputs – normalized_predictions).^2, ‘all’);
fprintf(‘MSE: %.4fn’, mse_loss);
%%
figure(‘units’,’normalized’,’outerposition’,[0 0 1 1])
plot(t,normalized_outputs,’r’);
grid;
hold on
plot(t,normalized_predictions,’–b’);
legend(‘Truth’,’NN’,’Location’,’best’);
set(gcf,’color’,’w’) neural network, neural networks, regression MATLAB Answers — New Questions
Why do I get “Unable to load Support Package information” when trying to download or install a Support Package in R2016b or previous releases?
Why do I get the following error when trying to download or install a Support Package using the Legacy Support Package Installer (R2016b and previous releases)?
Error: Select an actionUnable to load support package information.This may be due to network problems. Verify your network connection and retry the support package installation. If the problem persists, contact MathWorks Technical support.Why do I get the following error when trying to download or install a Support Package using the Legacy Support Package Installer (R2016b and previous releases)?
Error: Select an actionUnable to load support package information.This may be due to network problems. Verify your network connection and retry the support package installation. If the problem persists, contact MathWorks Technical support. Why do I get the following error when trying to download or install a Support Package using the Legacy Support Package Installer (R2016b and previous releases)?
Error: Select an actionUnable to load support package information.This may be due to network problems. Verify your network connection and retry the support package installation. If the problem persists, contact MathWorks Technical support. MATLAB Answers — New Questions
How to generate a P-V curve when changing the Open Circuit Voltage and Short Circuit Current Values in a Solar Cell module?
Hello,
I’m realatively new to simulink and I am trying to generate a P-V curve using a solar cell module and a variable resistor. Whenever I use the default values for Voc and Isc in the solar cell module, I get a P-V curve. However, when I change the Voc and Isc values in the solar cell, my plot shows a linear relationship instead of a curve. Is there a way to change the Voc and Isc values in the solar cell to have it display a correct P-V curve? I have provided my working Simulink model below. Thank you.Hello,
I’m realatively new to simulink and I am trying to generate a P-V curve using a solar cell module and a variable resistor. Whenever I use the default values for Voc and Isc in the solar cell module, I get a P-V curve. However, when I change the Voc and Isc values in the solar cell, my plot shows a linear relationship instead of a curve. Is there a way to change the Voc and Isc values in the solar cell to have it display a correct P-V curve? I have provided my working Simulink model below. Thank you. Hello,
I’m realatively new to simulink and I am trying to generate a P-V curve using a solar cell module and a variable resistor. Whenever I use the default values for Voc and Isc in the solar cell module, I get a P-V curve. However, when I change the Voc and Isc values in the solar cell, my plot shows a linear relationship instead of a curve. Is there a way to change the Voc and Isc values in the solar cell to have it display a correct P-V curve? I have provided my working Simulink model below. Thank you. solar cell, open circuit voltage, short circuit current MATLAB Answers — New Questions
Simulink CAN Error Handling on C2000
We’re developing autocoded C2000 firmware using Simulink. Our application relies heavily on CAN, but we’ve been having intermittent failiures where the firmware continues to run but the C2000 CAN peripheral seems to stop operating. We see no CAN messages until we restart the controller.
We can replicate the issue by temporarily shorting the CAN lines together, which would seem to confirm the CAN controller is being put into an error state and never recovering. Reading the datasheet, this is intended behavior. However, we need our device to continue transmitting no matter what.
How can we either set the CAN peripheral to auto-recover from errors or force a reset when an error is detected?We’re developing autocoded C2000 firmware using Simulink. Our application relies heavily on CAN, but we’ve been having intermittent failiures where the firmware continues to run but the C2000 CAN peripheral seems to stop operating. We see no CAN messages until we restart the controller.
We can replicate the issue by temporarily shorting the CAN lines together, which would seem to confirm the CAN controller is being put into an error state and never recovering. Reading the datasheet, this is intended behavior. However, we need our device to continue transmitting no matter what.
How can we either set the CAN peripheral to auto-recover from errors or force a reset when an error is detected? We’re developing autocoded C2000 firmware using Simulink. Our application relies heavily on CAN, but we’ve been having intermittent failiures where the firmware continues to run but the C2000 CAN peripheral seems to stop operating. We see no CAN messages until we restart the controller.
We can replicate the issue by temporarily shorting the CAN lines together, which would seem to confirm the CAN controller is being put into an error state and never recovering. Reading the datasheet, this is intended behavior. However, we need our device to continue transmitting no matter what.
How can we either set the CAN peripheral to auto-recover from errors or force a reset when an error is detected? can, c2000, simulink MATLAB Answers — New Questions
I need an algorithm to fill in the blank vertical path pixels.
I need an algorithm to fill in the blank vertical path pixels.I need an algorithm to fill in the blank vertical path pixels. I need an algorithm to fill in the blank vertical path pixels. complete lines, continuity, edge linking MATLAB Answers — New Questions
How to use loops to scan through pixels and black out the pixels outside a shape with a (white) perimeter (image)
I am attempting to use loops to check each pixel for whether or not its within a perimeter of white. Essentially I want to keep whats inside the white perimeter while blacking out everything else. I would like to do this using a loops rather than a mask if possible so I can apply this to other similar images (Different skin colors with same white perimeter). Below I have an image listed for example. In my attempt to loop through I found I could not make the loop skip over the area between the white lines and everything but the white parts would be blacked out. Below is the code I used to try and do this:
newI =(imread(nameF));
figure;
imshow(newI);
newB = newI(:,:,1);
for r = 1:size(newB,1)
for c = 1:size(newB,2)
pixel = newB(r,c);
current = c;
if pixel == 255
for cc = current:size(newB,2)
pixel2=(newB(r,cc));
if pixel2 == 255
skip = cc;
break
end
end
else
newI(r, c, 1) = 0;
newI(r, c, 2) = 0;
newI(r, c, 3) = 0;
end
c = skip;
end
end
figure
imshow(newI)I am attempting to use loops to check each pixel for whether or not its within a perimeter of white. Essentially I want to keep whats inside the white perimeter while blacking out everything else. I would like to do this using a loops rather than a mask if possible so I can apply this to other similar images (Different skin colors with same white perimeter). Below I have an image listed for example. In my attempt to loop through I found I could not make the loop skip over the area between the white lines and everything but the white parts would be blacked out. Below is the code I used to try and do this:
newI =(imread(nameF));
figure;
imshow(newI);
newB = newI(:,:,1);
for r = 1:size(newB,1)
for c = 1:size(newB,2)
pixel = newB(r,c);
current = c;
if pixel == 255
for cc = current:size(newB,2)
pixel2=(newB(r,cc));
if pixel2 == 255
skip = cc;
break
end
end
else
newI(r, c, 1) = 0;
newI(r, c, 2) = 0;
newI(r, c, 3) = 0;
end
c = skip;
end
end
figure
imshow(newI) I am attempting to use loops to check each pixel for whether or not its within a perimeter of white. Essentially I want to keep whats inside the white perimeter while blacking out everything else. I would like to do this using a loops rather than a mask if possible so I can apply this to other similar images (Different skin colors with same white perimeter). Below I have an image listed for example. In my attempt to loop through I found I could not make the loop skip over the area between the white lines and everything but the white parts would be blacked out. Below is the code I used to try and do this:
newI =(imread(nameF));
figure;
imshow(newI);
newB = newI(:,:,1);
for r = 1:size(newB,1)
for c = 1:size(newB,2)
pixel = newB(r,c);
current = c;
if pixel == 255
for cc = current:size(newB,2)
pixel2=(newB(r,cc));
if pixel2 == 255
skip = cc;
break
end
end
else
newI(r, c, 1) = 0;
newI(r, c, 2) = 0;
newI(r, c, 3) = 0;
end
c = skip;
end
end
figure
imshow(newI) image processing MATLAB Answers — New Questions
Problem with lsqnonlin and error function implementing a bovine pericardium constitutive model
I implemented a constitutive model for the bovine pericardium to be fit with experimental data to derive four model parameters. The code runs, but I have doubts about the correct implementation of the error function. Showing the iterations on the screen, I notice that at certain points the objective function returns nan or inf. I have checked the experimental data and in some cases there are values close to zero, but I don’t think this justifies the fact that the function converges, thus giving me the 4 parameters I am looking for, but without obtaining a decent fitting with the experimental data. Moreover, optimized parameters number 2 and 3 are assigned to lower bounds, while the first optimized parameter is very high. Below is the main and the error function.
Main:
clc; clear all;close all;
load ("data_11122.mat"); % change lot number if necessary
clearvars -except data
%Model requires lambda= x/x0 instead of epsilon: calculate lambda
% from exp data and store in data struct
stress=data(1).stress; %change index to change dogbone if necessary
strain=data(1).strain; %change index to change dogbone if necessary
% stress=stress/max(abs(stress));
% strain=strain/max(abs(strain));
p_initial=[0.5 0.5 0.5 0.5];
a0=[1 0 0];
%vincoli su zeta imposti da dong ( zeta tra 0 e 1 )
lb=[0.1 0.1 0.1 0.1];
ub=[inf inf inf inf];
%ottimizzazione non lineare con metodo least square ( like Dong )
options = optimoptions(‘lsqnonlin’, ‘Display’, ‘iter’, ‘Algorithm’,’levenberg-marquardt’);
[p_opt, resnorm] = lsqnonlin(@(p) error_function(p,strain,stress,a0), p_initial,lb,ub,options);
%check plot e ricostruzione del modello con i parametri ottimizzati
c = p_opt(1); % c
k1 = p_opt(2); % k1
k2 = p_opt(3); % k2
zeta = p_opt(4); % zeta
for i=1:length(strain)
f = [strain(i) 0 0; %deformation gradient for each value of strain
0 1/sqrt(strain(i)) 0;
0 0 1/sqrt(strain(i))];
C = f .* f’; % Calcola il tensore di Cauchy-Green
prod = a0 .* a0′;
I4 = sum(sum(C .* prod)); % calcolo invariante di C
I = eye(3); % Matrice identità
sigma = 2 * f * (c / 2 * I + k1 * (1 – zeta)^2 * (I4 – 1) * (exp(k2 * ((1 – zeta) * (I4 – 1))^2))) * prod .* f’;
sigma_calculated(i)= sigma(1,1); %componente xx
end
figure(1)
plot (strain,stress);
hold on
plot(strain, sigma_calculated,’r’);
legend (‘experimental’, ‘model’,’Location’, ‘northwest’);
Error function:
function error = error_function(p,strain,stress,a0,k)
sigma_calculated = zeros(length(strain), 1);
for i = 1:length(strain)
f = [strain(i) 0 0; %deformation gradient
0 1/sqrt(strain(i)) 0;
0 0 1/sqrt(strain(i))];
C = f .* f’; % tensore di Cauchy-Green
prod = a0 .* a0′;
I4 = a0′ .* C .* a0; % calcolo IV invariante di C
I = eye(3);
sigma = 2 * f * (p(1) / 2 * I + p(2) * (1 – p(4))^2 * (I4 – 1) * (exp(p(3) * ((1 – p(4)) * (I4 – 1))^2)) * prod) .* f’;
sigma_calculated(i)= sigma(1,1); %componente xx
end
%il calcolo dell’errore va dentro o fuori dal for?
error= sum((sigma_calculated(i) – stress(i))^2); % Somma dei quadrati delle differenze
% disp([‘Iterazione: ‘, num2str(k), ‘ – Errore totale attuale: ‘, num2str(error)]);
endI implemented a constitutive model for the bovine pericardium to be fit with experimental data to derive four model parameters. The code runs, but I have doubts about the correct implementation of the error function. Showing the iterations on the screen, I notice that at certain points the objective function returns nan or inf. I have checked the experimental data and in some cases there are values close to zero, but I don’t think this justifies the fact that the function converges, thus giving me the 4 parameters I am looking for, but without obtaining a decent fitting with the experimental data. Moreover, optimized parameters number 2 and 3 are assigned to lower bounds, while the first optimized parameter is very high. Below is the main and the error function.
Main:
clc; clear all;close all;
load ("data_11122.mat"); % change lot number if necessary
clearvars -except data
%Model requires lambda= x/x0 instead of epsilon: calculate lambda
% from exp data and store in data struct
stress=data(1).stress; %change index to change dogbone if necessary
strain=data(1).strain; %change index to change dogbone if necessary
% stress=stress/max(abs(stress));
% strain=strain/max(abs(strain));
p_initial=[0.5 0.5 0.5 0.5];
a0=[1 0 0];
%vincoli su zeta imposti da dong ( zeta tra 0 e 1 )
lb=[0.1 0.1 0.1 0.1];
ub=[inf inf inf inf];
%ottimizzazione non lineare con metodo least square ( like Dong )
options = optimoptions(‘lsqnonlin’, ‘Display’, ‘iter’, ‘Algorithm’,’levenberg-marquardt’);
[p_opt, resnorm] = lsqnonlin(@(p) error_function(p,strain,stress,a0), p_initial,lb,ub,options);
%check plot e ricostruzione del modello con i parametri ottimizzati
c = p_opt(1); % c
k1 = p_opt(2); % k1
k2 = p_opt(3); % k2
zeta = p_opt(4); % zeta
for i=1:length(strain)
f = [strain(i) 0 0; %deformation gradient for each value of strain
0 1/sqrt(strain(i)) 0;
0 0 1/sqrt(strain(i))];
C = f .* f’; % Calcola il tensore di Cauchy-Green
prod = a0 .* a0′;
I4 = sum(sum(C .* prod)); % calcolo invariante di C
I = eye(3); % Matrice identità
sigma = 2 * f * (c / 2 * I + k1 * (1 – zeta)^2 * (I4 – 1) * (exp(k2 * ((1 – zeta) * (I4 – 1))^2))) * prod .* f’;
sigma_calculated(i)= sigma(1,1); %componente xx
end
figure(1)
plot (strain,stress);
hold on
plot(strain, sigma_calculated,’r’);
legend (‘experimental’, ‘model’,’Location’, ‘northwest’);
Error function:
function error = error_function(p,strain,stress,a0,k)
sigma_calculated = zeros(length(strain), 1);
for i = 1:length(strain)
f = [strain(i) 0 0; %deformation gradient
0 1/sqrt(strain(i)) 0;
0 0 1/sqrt(strain(i))];
C = f .* f’; % tensore di Cauchy-Green
prod = a0 .* a0′;
I4 = a0′ .* C .* a0; % calcolo IV invariante di C
I = eye(3);
sigma = 2 * f * (p(1) / 2 * I + p(2) * (1 – p(4))^2 * (I4 – 1) * (exp(p(3) * ((1 – p(4)) * (I4 – 1))^2)) * prod) .* f’;
sigma_calculated(i)= sigma(1,1); %componente xx
end
%il calcolo dell’errore va dentro o fuori dal for?
error= sum((sigma_calculated(i) – stress(i))^2); % Somma dei quadrati delle differenze
% disp([‘Iterazione: ‘, num2str(k), ‘ – Errore totale attuale: ‘, num2str(error)]);
end I implemented a constitutive model for the bovine pericardium to be fit with experimental data to derive four model parameters. The code runs, but I have doubts about the correct implementation of the error function. Showing the iterations on the screen, I notice that at certain points the objective function returns nan or inf. I have checked the experimental data and in some cases there are values close to zero, but I don’t think this justifies the fact that the function converges, thus giving me the 4 parameters I am looking for, but without obtaining a decent fitting with the experimental data. Moreover, optimized parameters number 2 and 3 are assigned to lower bounds, while the first optimized parameter is very high. Below is the main and the error function.
Main:
clc; clear all;close all;
load ("data_11122.mat"); % change lot number if necessary
clearvars -except data
%Model requires lambda= x/x0 instead of epsilon: calculate lambda
% from exp data and store in data struct
stress=data(1).stress; %change index to change dogbone if necessary
strain=data(1).strain; %change index to change dogbone if necessary
% stress=stress/max(abs(stress));
% strain=strain/max(abs(strain));
p_initial=[0.5 0.5 0.5 0.5];
a0=[1 0 0];
%vincoli su zeta imposti da dong ( zeta tra 0 e 1 )
lb=[0.1 0.1 0.1 0.1];
ub=[inf inf inf inf];
%ottimizzazione non lineare con metodo least square ( like Dong )
options = optimoptions(‘lsqnonlin’, ‘Display’, ‘iter’, ‘Algorithm’,’levenberg-marquardt’);
[p_opt, resnorm] = lsqnonlin(@(p) error_function(p,strain,stress,a0), p_initial,lb,ub,options);
%check plot e ricostruzione del modello con i parametri ottimizzati
c = p_opt(1); % c
k1 = p_opt(2); % k1
k2 = p_opt(3); % k2
zeta = p_opt(4); % zeta
for i=1:length(strain)
f = [strain(i) 0 0; %deformation gradient for each value of strain
0 1/sqrt(strain(i)) 0;
0 0 1/sqrt(strain(i))];
C = f .* f’; % Calcola il tensore di Cauchy-Green
prod = a0 .* a0′;
I4 = sum(sum(C .* prod)); % calcolo invariante di C
I = eye(3); % Matrice identità
sigma = 2 * f * (c / 2 * I + k1 * (1 – zeta)^2 * (I4 – 1) * (exp(k2 * ((1 – zeta) * (I4 – 1))^2))) * prod .* f’;
sigma_calculated(i)= sigma(1,1); %componente xx
end
figure(1)
plot (strain,stress);
hold on
plot(strain, sigma_calculated,’r’);
legend (‘experimental’, ‘model’,’Location’, ‘northwest’);
Error function:
function error = error_function(p,strain,stress,a0,k)
sigma_calculated = zeros(length(strain), 1);
for i = 1:length(strain)
f = [strain(i) 0 0; %deformation gradient
0 1/sqrt(strain(i)) 0;
0 0 1/sqrt(strain(i))];
C = f .* f’; % tensore di Cauchy-Green
prod = a0 .* a0′;
I4 = a0′ .* C .* a0; % calcolo IV invariante di C
I = eye(3);
sigma = 2 * f * (p(1) / 2 * I + p(2) * (1 – p(4))^2 * (I4 – 1) * (exp(p(3) * ((1 – p(4)) * (I4 – 1))^2)) * prod) .* f’;
sigma_calculated(i)= sigma(1,1); %componente xx
end
%il calcolo dell’errore va dentro o fuori dal for?
error= sum((sigma_calculated(i) – stress(i))^2); % Somma dei quadrati delle differenze
% disp([‘Iterazione: ‘, num2str(k), ‘ – Errore totale attuale: ‘, num2str(error)]);
end curve fitting, nonlinear, soft tissue MATLAB Answers — New Questions
simFunction anf dose Array from an input file
Hi. After fitting my model (fitting was successful using sbiofit) I wrote the code below to generate simfunction to run the model with estimated values and the parmetr in the gData for each case.In gData the doses has been detemined and they are diffent rated doses for each patient applied at diffent time points. I was not able to pass dosesForFit = createDoses(gData, ‘DOSE’, ‘dose_rate’, d3) to simfunction because Invalid dosing information. Specify doses as a row vector. and then I used dosesForFit = reshape(dosesForFit, 1, []); % Ensure dosesForFit is a row vector and the problem solved and simFunction was executed but the dose considered the same for all of the cases and was combinatin of all of the doses. How can I solve this problem. I attached input file and the code is below: Thanks
%% Update Parameters with Estimated Values and Running the Model
d3 = sbiodose(‘DOSE’);
d3.TargetName = ‘plasma.A1’;
d3.LagParameterName = ”;
d3.AmountUnits = ‘nanomole’;
d3.RateUnits = ‘nanomole/day’;
d3.TimeUnits=configsetObj.TimeUnits;
dosesForFit = createDoses(gData, ‘DOSE’, ‘dose_rate’, d3);
dosesForFit = reshape(dosesForFit, 1, []); % Ensure dosesForFit is a row vector
doseTable = getTable(dosesForFit);
% getTable(dosesForFit)
% Extract Observables and Experimental Data
for i = 1:length(fitResults.EstimatedParameterNames)
paramObj = sbioselect(model, ‘Name’, fitResults.EstimatedParameterNames{i});
paramObj.Value = fitResults.ParameterEstimates.Estimate(i);
end
% Define parameter names to extract
variantParams = {‘BW’, ‘SLD’, ‘HSCR’, ‘FRAPS’};
% Extract IDs in the order they appear in the input file
idsInOrder = exp_data.ID; % Retain original ID order
[uniqueIDs, ~, idOrder] = unique(idsInOrder, ‘stable’); % Preserve order from input file
% Initialize paramMatrix with zeros
numIDs = length(uniqueIDs);
paramMatrix = zeros(numIDs, length(variantParams)); % Rows for IDs, columns for parameters
% Populate paramMatrix with parameter values based on the input file order
for i = 1:numIDs
% Filter data for the current ID
currentID = uniqueIDs(i);
idData = exp_data(exp_data.ID == currentID, :);
% Assign parameter values (assume these are constant per ID)
paramMatrix(i, 🙂 = [idData.BW(1), idData.SLD(1), idData.HSCR(1), idData.FRAPS(1)];
end
% Observables for the simulation
obs = {‘CAb_plasma’, ‘CADC_plasma’, ‘CPLun_plasma’}; % Observables to track
% Create SimFunction
sfxn = createSimFunction(model, variantParams, obs, dosesForFit,’UseParallel’, true, ‘AutoAccelerate’, true);
% Simulate Using the Parameter Matrix
% Create dose table from dosesForFit
% Simulate the model using the parameter matrix
simData = sfxn(paramMatrix, [], doseTable, time);Hi. After fitting my model (fitting was successful using sbiofit) I wrote the code below to generate simfunction to run the model with estimated values and the parmetr in the gData for each case.In gData the doses has been detemined and they are diffent rated doses for each patient applied at diffent time points. I was not able to pass dosesForFit = createDoses(gData, ‘DOSE’, ‘dose_rate’, d3) to simfunction because Invalid dosing information. Specify doses as a row vector. and then I used dosesForFit = reshape(dosesForFit, 1, []); % Ensure dosesForFit is a row vector and the problem solved and simFunction was executed but the dose considered the same for all of the cases and was combinatin of all of the doses. How can I solve this problem. I attached input file and the code is below: Thanks
%% Update Parameters with Estimated Values and Running the Model
d3 = sbiodose(‘DOSE’);
d3.TargetName = ‘plasma.A1’;
d3.LagParameterName = ”;
d3.AmountUnits = ‘nanomole’;
d3.RateUnits = ‘nanomole/day’;
d3.TimeUnits=configsetObj.TimeUnits;
dosesForFit = createDoses(gData, ‘DOSE’, ‘dose_rate’, d3);
dosesForFit = reshape(dosesForFit, 1, []); % Ensure dosesForFit is a row vector
doseTable = getTable(dosesForFit);
% getTable(dosesForFit)
% Extract Observables and Experimental Data
for i = 1:length(fitResults.EstimatedParameterNames)
paramObj = sbioselect(model, ‘Name’, fitResults.EstimatedParameterNames{i});
paramObj.Value = fitResults.ParameterEstimates.Estimate(i);
end
% Define parameter names to extract
variantParams = {‘BW’, ‘SLD’, ‘HSCR’, ‘FRAPS’};
% Extract IDs in the order they appear in the input file
idsInOrder = exp_data.ID; % Retain original ID order
[uniqueIDs, ~, idOrder] = unique(idsInOrder, ‘stable’); % Preserve order from input file
% Initialize paramMatrix with zeros
numIDs = length(uniqueIDs);
paramMatrix = zeros(numIDs, length(variantParams)); % Rows for IDs, columns for parameters
% Populate paramMatrix with parameter values based on the input file order
for i = 1:numIDs
% Filter data for the current ID
currentID = uniqueIDs(i);
idData = exp_data(exp_data.ID == currentID, :);
% Assign parameter values (assume these are constant per ID)
paramMatrix(i, 🙂 = [idData.BW(1), idData.SLD(1), idData.HSCR(1), idData.FRAPS(1)];
end
% Observables for the simulation
obs = {‘CAb_plasma’, ‘CADC_plasma’, ‘CPLun_plasma’}; % Observables to track
% Create SimFunction
sfxn = createSimFunction(model, variantParams, obs, dosesForFit,’UseParallel’, true, ‘AutoAccelerate’, true);
% Simulate Using the Parameter Matrix
% Create dose table from dosesForFit
% Simulate the model using the parameter matrix
simData = sfxn(paramMatrix, [], doseTable, time); Hi. After fitting my model (fitting was successful using sbiofit) I wrote the code below to generate simfunction to run the model with estimated values and the parmetr in the gData for each case.In gData the doses has been detemined and they are diffent rated doses for each patient applied at diffent time points. I was not able to pass dosesForFit = createDoses(gData, ‘DOSE’, ‘dose_rate’, d3) to simfunction because Invalid dosing information. Specify doses as a row vector. and then I used dosesForFit = reshape(dosesForFit, 1, []); % Ensure dosesForFit is a row vector and the problem solved and simFunction was executed but the dose considered the same for all of the cases and was combinatin of all of the doses. How can I solve this problem. I attached input file and the code is below: Thanks
%% Update Parameters with Estimated Values and Running the Model
d3 = sbiodose(‘DOSE’);
d3.TargetName = ‘plasma.A1’;
d3.LagParameterName = ”;
d3.AmountUnits = ‘nanomole’;
d3.RateUnits = ‘nanomole/day’;
d3.TimeUnits=configsetObj.TimeUnits;
dosesForFit = createDoses(gData, ‘DOSE’, ‘dose_rate’, d3);
dosesForFit = reshape(dosesForFit, 1, []); % Ensure dosesForFit is a row vector
doseTable = getTable(dosesForFit);
% getTable(dosesForFit)
% Extract Observables and Experimental Data
for i = 1:length(fitResults.EstimatedParameterNames)
paramObj = sbioselect(model, ‘Name’, fitResults.EstimatedParameterNames{i});
paramObj.Value = fitResults.ParameterEstimates.Estimate(i);
end
% Define parameter names to extract
variantParams = {‘BW’, ‘SLD’, ‘HSCR’, ‘FRAPS’};
% Extract IDs in the order they appear in the input file
idsInOrder = exp_data.ID; % Retain original ID order
[uniqueIDs, ~, idOrder] = unique(idsInOrder, ‘stable’); % Preserve order from input file
% Initialize paramMatrix with zeros
numIDs = length(uniqueIDs);
paramMatrix = zeros(numIDs, length(variantParams)); % Rows for IDs, columns for parameters
% Populate paramMatrix with parameter values based on the input file order
for i = 1:numIDs
% Filter data for the current ID
currentID = uniqueIDs(i);
idData = exp_data(exp_data.ID == currentID, :);
% Assign parameter values (assume these are constant per ID)
paramMatrix(i, 🙂 = [idData.BW(1), idData.SLD(1), idData.HSCR(1), idData.FRAPS(1)];
end
% Observables for the simulation
obs = {‘CAb_plasma’, ‘CADC_plasma’, ‘CPLun_plasma’}; % Observables to track
% Create SimFunction
sfxn = createSimFunction(model, variantParams, obs, dosesForFit,’UseParallel’, true, ‘AutoAccelerate’, true);
% Simulate Using the Parameter Matrix
% Create dose table from dosesForFit
% Simulate the model using the parameter matrix
simData = sfxn(paramMatrix, [], doseTable, time); simfunction and array doses MATLAB Answers — New Questions
Color input to comm.ConstellationDiagram object
I want to display the scatterplots of 2 different users in my simulation in real-time, for which I am using the comm.ConstellationDiagram object. I would like to use different colours for each user’s scatterplot to distinguish between them. However, comm.ConstellationDiagram does not take a color input.
Scatterplot function takes a color input, but I don’t want the plots on different figures each time I call it. I want the points plotted in real-time in the same figure (for each user), this is why I am using the comm.ConstellationDiagram object.
Here’s a snippet of how I am using it:
constDiag1 = comm.ConstellationDiagram(2, …
"ChannelNames",{‘Header’,’Data’}, …
"ReferenceConstellation",{refConstHeader,refConstData1}, …
"ShowLegend",true, …
"EnableMeasurements",true,…
"Title",’User 1 constellation’);
constDiag2 = comm.ConstellationDiagram(2, …
"ChannelNames",{‘Header’,’Data’}, …
"ReferenceConstellation",{refConstHeader,refConstData2}, …
"ShowLegend",true, …
"EnableMeasurements",true,…
"Title",’User 2 constellation’);
for frame=1:framenum
[rxHeader1,rxData1,rxHeader2,rxData2] = myfunction(captureData);
constDiag1(complex(rxHeader1(:)), …
complex(rxData1(:)));
constDiag2(complex(rxHeader2(:)), …
complex(rxData2(:)));
end
Is there a way to include a colour input to the configuration of the object?
If not, how can I go about making a custom function for obtaining scatterplots in real-time (similar to what comm.ConstellationDiagram does) where I can configure each object in a different color?
Thanks! Any help is appreciated!I want to display the scatterplots of 2 different users in my simulation in real-time, for which I am using the comm.ConstellationDiagram object. I would like to use different colours for each user’s scatterplot to distinguish between them. However, comm.ConstellationDiagram does not take a color input.
Scatterplot function takes a color input, but I don’t want the plots on different figures each time I call it. I want the points plotted in real-time in the same figure (for each user), this is why I am using the comm.ConstellationDiagram object.
Here’s a snippet of how I am using it:
constDiag1 = comm.ConstellationDiagram(2, …
"ChannelNames",{‘Header’,’Data’}, …
"ReferenceConstellation",{refConstHeader,refConstData1}, …
"ShowLegend",true, …
"EnableMeasurements",true,…
"Title",’User 1 constellation’);
constDiag2 = comm.ConstellationDiagram(2, …
"ChannelNames",{‘Header’,’Data’}, …
"ReferenceConstellation",{refConstHeader,refConstData2}, …
"ShowLegend",true, …
"EnableMeasurements",true,…
"Title",’User 2 constellation’);
for frame=1:framenum
[rxHeader1,rxData1,rxHeader2,rxData2] = myfunction(captureData);
constDiag1(complex(rxHeader1(:)), …
complex(rxData1(:)));
constDiag2(complex(rxHeader2(:)), …
complex(rxData2(:)));
end
Is there a way to include a colour input to the configuration of the object?
If not, how can I go about making a custom function for obtaining scatterplots in real-time (similar to what comm.ConstellationDiagram does) where I can configure each object in a different color?
Thanks! Any help is appreciated! I want to display the scatterplots of 2 different users in my simulation in real-time, for which I am using the comm.ConstellationDiagram object. I would like to use different colours for each user’s scatterplot to distinguish between them. However, comm.ConstellationDiagram does not take a color input.
Scatterplot function takes a color input, but I don’t want the plots on different figures each time I call it. I want the points plotted in real-time in the same figure (for each user), this is why I am using the comm.ConstellationDiagram object.
Here’s a snippet of how I am using it:
constDiag1 = comm.ConstellationDiagram(2, …
"ChannelNames",{‘Header’,’Data’}, …
"ReferenceConstellation",{refConstHeader,refConstData1}, …
"ShowLegend",true, …
"EnableMeasurements",true,…
"Title",’User 1 constellation’);
constDiag2 = comm.ConstellationDiagram(2, …
"ChannelNames",{‘Header’,’Data’}, …
"ReferenceConstellation",{refConstHeader,refConstData2}, …
"ShowLegend",true, …
"EnableMeasurements",true,…
"Title",’User 2 constellation’);
for frame=1:framenum
[rxHeader1,rxData1,rxHeader2,rxData2] = myfunction(captureData);
constDiag1(complex(rxHeader1(:)), …
complex(rxData1(:)));
constDiag2(complex(rxHeader2(:)), …
complex(rxData2(:)));
end
Is there a way to include a colour input to the configuration of the object?
If not, how can I go about making a custom function for obtaining scatterplots in real-time (similar to what comm.ConstellationDiagram does) where I can configure each object in a different color?
Thanks! Any help is appreciated! scatterplot, constellation diagram, plotting in real-time, scatterplot colour MATLAB Answers — New Questions
PMSM speed ramp input with V/f scalar control does not work
Hi,
I’m trying to implement a V/f scalar control for a PMSM, for speed step input there is no problem and the motor model works fine up until 2000 rpm more or less. But I want to set a reference speed that follows a ramp but somehow the motor becomes unstable way earlier than expected and the motor speed whas a different slope than the reference speed and I dont know why.
For instances this is the motor behavior under different speeds:
(also not sure why there are this huge speed drops at some step inputs)
And this is how it responds to a ramp input:
So, Why does the motor becomes unstable before thatn predicted when its subjected to a ramp input? Why does it have a different slope than the reference signal?
I have attached the simulink model along with the script that it is referenced to.Hi,
I’m trying to implement a V/f scalar control for a PMSM, for speed step input there is no problem and the motor model works fine up until 2000 rpm more or less. But I want to set a reference speed that follows a ramp but somehow the motor becomes unstable way earlier than expected and the motor speed whas a different slope than the reference speed and I dont know why.
For instances this is the motor behavior under different speeds:
(also not sure why there are this huge speed drops at some step inputs)
And this is how it responds to a ramp input:
So, Why does the motor becomes unstable before thatn predicted when its subjected to a ramp input? Why does it have a different slope than the reference signal?
I have attached the simulink model along with the script that it is referenced to. Hi,
I’m trying to implement a V/f scalar control for a PMSM, for speed step input there is no problem and the motor model works fine up until 2000 rpm more or less. But I want to set a reference speed that follows a ramp but somehow the motor becomes unstable way earlier than expected and the motor speed whas a different slope than the reference speed and I dont know why.
For instances this is the motor behavior under different speeds:
(also not sure why there are this huge speed drops at some step inputs)
And this is how it responds to a ramp input:
So, Why does the motor becomes unstable before thatn predicted when its subjected to a ramp input? Why does it have a different slope than the reference signal?
I have attached the simulink model along with the script that it is referenced to. pmsm scalar control, pmsm v/f control, pmsm speed response with scalar control, pmsm speed response with v/f control MATLAB Answers — New Questions
Gate Driver – How to incorporate bootstrap circuitry?
I am attempting to use two of the Gate Driver symbol in Simscape to model my selected half-bridge driver. I am using two Gate Driver symbols because it appears the Half-Bridge Driver symbol only accepts one input; in my system, there will be two discrete inputs to the driver.
I do not see from the connections available on the Gate Driver symbol how I would implement bootstrap circuitry to properly bias the upper MOSFET in my half-bridge.
Bootstrap circuitry referring to the highlighted elements shown below:
Thanks!
-MI am attempting to use two of the Gate Driver symbol in Simscape to model my selected half-bridge driver. I am using two Gate Driver symbols because it appears the Half-Bridge Driver symbol only accepts one input; in my system, there will be two discrete inputs to the driver.
I do not see from the connections available on the Gate Driver symbol how I would implement bootstrap circuitry to properly bias the upper MOSFET in my half-bridge.
Bootstrap circuitry referring to the highlighted elements shown below:
Thanks!
-M I am attempting to use two of the Gate Driver symbol in Simscape to model my selected half-bridge driver. I am using two Gate Driver symbols because it appears the Half-Bridge Driver symbol only accepts one input; in my system, there will be two discrete inputs to the driver.
I do not see from the connections available on the Gate Driver symbol how I would implement bootstrap circuitry to properly bias the upper MOSFET in my half-bridge.
Bootstrap circuitry referring to the highlighted elements shown below:
Thanks!
-M simscape, gate driver, half-bridge MATLAB Answers — New Questions
Is it possible to ‘interpolate’ in FFT data?
We kmow OTF and PSF are continuous, can be interpolate inside it (<cutoff freq ) even when we express them wIth matrix use integer row&col coordinate .
now I have a image, and get its FFT2, and find some feature like max or min only with row and col,
but I know true max or min not at that integer row and col exactly, It is really at a fraction position near that integer row and col in matrix.
How to get it if I know fraction or decimal position ?
In frequency domain, can exten matrix size with 0, but can not interpolate although we can interpolate at time domain.
How to do ?
Maybe I can do so like such method : in time domain , matrix .* with exp( – j ke), {ke is a decimal number part }, to realize freq shift effect, after that, FFT, now at that row&col coordinate really is a value corresponding to [ row&col + decimal ke ] position, so I get it .
Such idea is right ? I am not expert at FFT, who can tell me , Is it Right ?
or how to find the feature not exactly at discrete integer row&col coordinate ?
I need some value at real flot number row&col coordinate ?
—————————————————————————————————————–
I mean :
For simple example:
there are 512 data point with coordinate 1~512, transfer to freq domain with FFT, it is 512 mag and phase with coordinate -256~255 * 1/256 .
now if I specially add a cosine wave with freq 180.324 *1/512 to 512 data point (I used it as a special inner reference), then transfer to freq domain with FFT.
here , how to find mag and phase information of this added cosine wave in freq domain ?
freq 180.324 , is not a integer -256~255 coordinate, so how to find it ?
sample code:
% Time domain
t = linspace(1,512,512);
g = 2*sin(2*pi*t*16/512) + 0.5*sin(2*pi*t*64/512)+ 0.4*sin(2*pi*t*128/512);
gadd = g+0.2*cos(2*pi*t*180.327/512);
%gadd = g+5*sin(2*pi*t*180.327/512);
% now add 180.324 or any another not N/512
subplot(2,2,1);
plot(g);
title("Time domain 3 sin")
subplot(2,2,2);
plot(g);
title("Time domain, 3 sin + cos")
fco = linspace(-256,255,512);
F=fftshift(fft(g));
F1=fftshift(fft(gadd));
subplot(2,2,3);
stem (fco,real(F));
title("Freq domain, 3 sin")
subplot(2,2,4);
stem (fco,real(F1));
title("Freq domain, 3 sin + cos")
% how to find that 180.327 accuratly ?We kmow OTF and PSF are continuous, can be interpolate inside it (<cutoff freq ) even when we express them wIth matrix use integer row&col coordinate .
now I have a image, and get its FFT2, and find some feature like max or min only with row and col,
but I know true max or min not at that integer row and col exactly, It is really at a fraction position near that integer row and col in matrix.
How to get it if I know fraction or decimal position ?
In frequency domain, can exten matrix size with 0, but can not interpolate although we can interpolate at time domain.
How to do ?
Maybe I can do so like such method : in time domain , matrix .* with exp( – j ke), {ke is a decimal number part }, to realize freq shift effect, after that, FFT, now at that row&col coordinate really is a value corresponding to [ row&col + decimal ke ] position, so I get it .
Such idea is right ? I am not expert at FFT, who can tell me , Is it Right ?
or how to find the feature not exactly at discrete integer row&col coordinate ?
I need some value at real flot number row&col coordinate ?
—————————————————————————————————————–
I mean :
For simple example:
there are 512 data point with coordinate 1~512, transfer to freq domain with FFT, it is 512 mag and phase with coordinate -256~255 * 1/256 .
now if I specially add a cosine wave with freq 180.324 *1/512 to 512 data point (I used it as a special inner reference), then transfer to freq domain with FFT.
here , how to find mag and phase information of this added cosine wave in freq domain ?
freq 180.324 , is not a integer -256~255 coordinate, so how to find it ?
sample code:
% Time domain
t = linspace(1,512,512);
g = 2*sin(2*pi*t*16/512) + 0.5*sin(2*pi*t*64/512)+ 0.4*sin(2*pi*t*128/512);
gadd = g+0.2*cos(2*pi*t*180.327/512);
%gadd = g+5*sin(2*pi*t*180.327/512);
% now add 180.324 or any another not N/512
subplot(2,2,1);
plot(g);
title("Time domain 3 sin")
subplot(2,2,2);
plot(g);
title("Time domain, 3 sin + cos")
fco = linspace(-256,255,512);
F=fftshift(fft(g));
F1=fftshift(fft(gadd));
subplot(2,2,3);
stem (fco,real(F));
title("Freq domain, 3 sin")
subplot(2,2,4);
stem (fco,real(F1));
title("Freq domain, 3 sin + cos")
% how to find that 180.327 accuratly ? We kmow OTF and PSF are continuous, can be interpolate inside it (<cutoff freq ) even when we express them wIth matrix use integer row&col coordinate .
now I have a image, and get its FFT2, and find some feature like max or min only with row and col,
but I know true max or min not at that integer row and col exactly, It is really at a fraction position near that integer row and col in matrix.
How to get it if I know fraction or decimal position ?
In frequency domain, can exten matrix size with 0, but can not interpolate although we can interpolate at time domain.
How to do ?
Maybe I can do so like such method : in time domain , matrix .* with exp( – j ke), {ke is a decimal number part }, to realize freq shift effect, after that, FFT, now at that row&col coordinate really is a value corresponding to [ row&col + decimal ke ] position, so I get it .
Such idea is right ? I am not expert at FFT, who can tell me , Is it Right ?
or how to find the feature not exactly at discrete integer row&col coordinate ?
I need some value at real flot number row&col coordinate ?
—————————————————————————————————————–
I mean :
For simple example:
there are 512 data point with coordinate 1~512, transfer to freq domain with FFT, it is 512 mag and phase with coordinate -256~255 * 1/256 .
now if I specially add a cosine wave with freq 180.324 *1/512 to 512 data point (I used it as a special inner reference), then transfer to freq domain with FFT.
here , how to find mag and phase information of this added cosine wave in freq domain ?
freq 180.324 , is not a integer -256~255 coordinate, so how to find it ?
sample code:
% Time domain
t = linspace(1,512,512);
g = 2*sin(2*pi*t*16/512) + 0.5*sin(2*pi*t*64/512)+ 0.4*sin(2*pi*t*128/512);
gadd = g+0.2*cos(2*pi*t*180.327/512);
%gadd = g+5*sin(2*pi*t*180.327/512);
% now add 180.324 or any another not N/512
subplot(2,2,1);
plot(g);
title("Time domain 3 sin")
subplot(2,2,2);
plot(g);
title("Time domain, 3 sin + cos")
fco = linspace(-256,255,512);
F=fftshift(fft(g));
F1=fftshift(fft(gadd));
subplot(2,2,3);
stem (fco,real(F));
title("Freq domain, 3 sin")
subplot(2,2,4);
stem (fco,real(F1));
title("Freq domain, 3 sin + cos")
% how to find that 180.327 accuratly ? fft, interpolate, discrete, continuous MATLAB Answers — New Questions
how to have a matlab script give you a choice to automatically open other scripts
Hi, I want to have a starting script where it allows me to open a different script. For example I want the main script to ask me, do you wish to follow procedure A? and then if I select yes, then automatically the matlab will open script A. If the main script asks, do you wish procedure B? then Matlab opens automatically script B and so on. Then once in the secondary script, I will enter the parameters needed to perform the calculation. Thank you.Hi, I want to have a starting script where it allows me to open a different script. For example I want the main script to ask me, do you wish to follow procedure A? and then if I select yes, then automatically the matlab will open script A. If the main script asks, do you wish procedure B? then Matlab opens automatically script B and so on. Then once in the secondary script, I will enter the parameters needed to perform the calculation. Thank you. Hi, I want to have a starting script where it allows me to open a different script. For example I want the main script to ask me, do you wish to follow procedure A? and then if I select yes, then automatically the matlab will open script A. If the main script asks, do you wish procedure B? then Matlab opens automatically script B and so on. Then once in the secondary script, I will enter the parameters needed to perform the calculation. Thank you. script MATLAB Answers — New Questions
Combine several matrix with NaNs
I need to combine several matrixes of 500×500 elements that contains NaN. The matrixes must be combined in the way they keep their size but replace NaN by the elements of the other matrix.
I can easily do it for two matrixes:
% Cx is a strucutre that I use to store these matrixes. Cx has several matrixes e.g Cx(1).Z Cx(2).Z …
or=Cx(1).Z; %I want to add the elements to the first matrix (or)
nr=Cx(2).Z; % this is the second matrix
xn=isnan(or); %I select the NaN’s
or(xn)=nr(xn); %I can get now combined elements between Cx(1).Z and Cx(2).Z, it works good until here
%I need to do the same now for all the other matrixes in my structure (Cx),so the combination will be cummulative, I mean use the resulting matrix from merging Cx(1).Z and Cx(2).Z to merge with Cx(3).Z, and then use this output to merge with Cx(4).Z …. and so on
I tough that a loop would be usefull
or=Cx(1).Z;
xn=isnan(or);
for i=1:numel(Cx)
nr=Cx(i).Z;
or(xn)=nr(xn);
end
but the output or is constantly overwrited and I can get a combination of the matrixes
any suggestion?
thanks in advanceI need to combine several matrixes of 500×500 elements that contains NaN. The matrixes must be combined in the way they keep their size but replace NaN by the elements of the other matrix.
I can easily do it for two matrixes:
% Cx is a strucutre that I use to store these matrixes. Cx has several matrixes e.g Cx(1).Z Cx(2).Z …
or=Cx(1).Z; %I want to add the elements to the first matrix (or)
nr=Cx(2).Z; % this is the second matrix
xn=isnan(or); %I select the NaN’s
or(xn)=nr(xn); %I can get now combined elements between Cx(1).Z and Cx(2).Z, it works good until here
%I need to do the same now for all the other matrixes in my structure (Cx),so the combination will be cummulative, I mean use the resulting matrix from merging Cx(1).Z and Cx(2).Z to merge with Cx(3).Z, and then use this output to merge with Cx(4).Z …. and so on
I tough that a loop would be usefull
or=Cx(1).Z;
xn=isnan(or);
for i=1:numel(Cx)
nr=Cx(i).Z;
or(xn)=nr(xn);
end
but the output or is constantly overwrited and I can get a combination of the matrixes
any suggestion?
thanks in advance I need to combine several matrixes of 500×500 elements that contains NaN. The matrixes must be combined in the way they keep their size but replace NaN by the elements of the other matrix.
I can easily do it for two matrixes:
% Cx is a strucutre that I use to store these matrixes. Cx has several matrixes e.g Cx(1).Z Cx(2).Z …
or=Cx(1).Z; %I want to add the elements to the first matrix (or)
nr=Cx(2).Z; % this is the second matrix
xn=isnan(or); %I select the NaN’s
or(xn)=nr(xn); %I can get now combined elements between Cx(1).Z and Cx(2).Z, it works good until here
%I need to do the same now for all the other matrixes in my structure (Cx),so the combination will be cummulative, I mean use the resulting matrix from merging Cx(1).Z and Cx(2).Z to merge with Cx(3).Z, and then use this output to merge with Cx(4).Z …. and so on
I tough that a loop would be usefull
or=Cx(1).Z;
xn=isnan(or);
for i=1:numel(Cx)
nr=Cx(i).Z;
or(xn)=nr(xn);
end
but the output or is constantly overwrited and I can get a combination of the matrixes
any suggestion?
thanks in advance matlab, matrix, nan, for loop MATLAB Answers — New Questions