Tag Archives: matlab
Save in an array lines after the appearance of a text pattern
Dear all
I was wondering which could be a good method to store in an array the first two columns of the first two lines after the line "Cell (Angstrom):" in the attached file.Dear all
I was wondering which could be a good method to store in an array the first two columns of the first two lines after the line "Cell (Angstrom):" in the attached file. Dear all
I was wondering which could be a good method to store in an array the first two columns of the first two lines after the line "Cell (Angstrom):" in the attached file. text pattern MATLAB Answers — New Questions
how to give input automatically
i have found accuracy and error from nerual network,i have trained the data,i have to give input one by one for several combination as 1,2..1,3..1,4…..1,100..to find accuracy and error..i sholud not give input my myself,it should be done automatically.in train data i have values from of combination 1,2..2,3..1,4…………1,100
i need all datas to be dispalyed with accuracy and errori have found accuracy and error from nerual network,i have trained the data,i have to give input one by one for several combination as 1,2..1,3..1,4…..1,100..to find accuracy and error..i sholud not give input my myself,it should be done automatically.in train data i have values from of combination 1,2..2,3..1,4…………1,100
i need all datas to be dispalyed with accuracy and error i have found accuracy and error from nerual network,i have trained the data,i have to give input one by one for several combination as 1,2..1,3..1,4…..1,100..to find accuracy and error..i sholud not give input my myself,it should be done automatically.in train data i have values from of combination 1,2..2,3..1,4…………1,100
i need all datas to be dispalyed with accuracy and error datamining MATLAB Answers — New Questions
How to remove gaps in timeseries plot to have a continuous graph
Hello Everyone,
I have a timeseries data from a vehicle having gaps in it. FOr example, when the vehicle was running, there is data, but no data is available when the vehicle is turned off. When i plot now, the missig data is filled witha line connecting last measured data to the next measured data (see figure). How can i remove that line and instead have a continuous line.
I highly appreciate for any efforts.Hello Everyone,
I have a timeseries data from a vehicle having gaps in it. FOr example, when the vehicle was running, there is data, but no data is available when the vehicle is turned off. When i plot now, the missig data is filled witha line connecting last measured data to the next measured data (see figure). How can i remove that line and instead have a continuous line.
I highly appreciate for any efforts. Hello Everyone,
I have a timeseries data from a vehicle having gaps in it. FOr example, when the vehicle was running, there is data, but no data is available when the vehicle is turned off. When i plot now, the missig data is filled witha line connecting last measured data to the next measured data (see figure). How can i remove that line and instead have a continuous line.
I highly appreciate for any efforts. timeseries, data handling, matlab plots MATLAB Answers — New Questions
Plot values on a x-y plane from excel – with colorbar
I would like to plot a x-y values from the excel attached on a plane.
I need a colorbar and Latex font.
Thanks everyone!I would like to plot a x-y values from the excel attached on a plane.
I need a colorbar and Latex font.
Thanks everyone! I would like to plot a x-y values from the excel attached on a plane.
I need a colorbar and Latex font.
Thanks everyone! plot, plotting, excel MATLAB Answers — New Questions
How to Calculate Higher-Order Derivatives
There exists a fifth-order implicit function (curve) such that f(x,y)=a (a is a constant)
For example, x^5+x^4*y^1+x^3*y^2+x^2*y^3+x^1*y^4+y^5=10
There exists a 3-dimensional surface such that g(x,y)=z.
For example, z=x^5+xy+y^5
Next, find the cubic curve g(x,y)=z along f(x,y)=a
Then, on the curve z, we want to find (x,y) where dz/dx=0 and dz/dy=0.There exists a fifth-order implicit function (curve) such that f(x,y)=a (a is a constant)
For example, x^5+x^4*y^1+x^3*y^2+x^2*y^3+x^1*y^4+y^5=10
There exists a 3-dimensional surface such that g(x,y)=z.
For example, z=x^5+xy+y^5
Next, find the cubic curve g(x,y)=z along f(x,y)=a
Then, on the curve z, we want to find (x,y) where dz/dx=0 and dz/dy=0. There exists a fifth-order implicit function (curve) such that f(x,y)=a (a is a constant)
For example, x^5+x^4*y^1+x^3*y^2+x^2*y^3+x^1*y^4+y^5=10
There exists a 3-dimensional surface such that g(x,y)=z.
For example, z=x^5+xy+y^5
Next, find the cubic curve g(x,y)=z along f(x,y)=a
Then, on the curve z, we want to find (x,y) where dz/dx=0 and dz/dy=0. implicit function, 3d surface, 2d curve, diff MATLAB Answers — New Questions
Entering Non-Linear System of Equations
Hi All. I am fairly new to Matlab and still learning. I am wondering if one may explain to me how I should enter a system of non-linear equations. For instance the equations I have are: 4*x(1)-x(2)+x(3)-x(1)*x(4) = 0; -x(1)+3*x(2)-2*x(3)-x(2)*x(4) = 0; and x(1)^2+x(2)^2+x(3)^2-1 = 0. Basically I want to enter the equations and use the Newton Method to solve using the Jacobian Matrix. This is how I enetered them in Matlab:
clear all
clc
syms x
f1 = 4*x(1)-x(2)+x(3)-x(1)*x(4);
f2 = -x(1)+3*x(2)-2*x(3)-x(2)*x(4);
f3 = x(1)^2+x(2)^2+x(3)^2-1;
F = [f1;f2;f3];
If I tell the program to run at this point, this is the error I happen to get:
??? Error using ==> mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.
Error in ==> sym.sym>sym.subsref at 1366
B = mupadmex(‘mllib::subsref’,A.s,inds{:});
Error in ==> NewtonMethosNonLinear at 5
f1 = 4*x(1)-x(2)+x(3)-x(1)*x(4);
I would appreciate some explanation on this since I don’t know how to move next. Thank you.Hi All. I am fairly new to Matlab and still learning. I am wondering if one may explain to me how I should enter a system of non-linear equations. For instance the equations I have are: 4*x(1)-x(2)+x(3)-x(1)*x(4) = 0; -x(1)+3*x(2)-2*x(3)-x(2)*x(4) = 0; and x(1)^2+x(2)^2+x(3)^2-1 = 0. Basically I want to enter the equations and use the Newton Method to solve using the Jacobian Matrix. This is how I enetered them in Matlab:
clear all
clc
syms x
f1 = 4*x(1)-x(2)+x(3)-x(1)*x(4);
f2 = -x(1)+3*x(2)-2*x(3)-x(2)*x(4);
f3 = x(1)^2+x(2)^2+x(3)^2-1;
F = [f1;f2;f3];
If I tell the program to run at this point, this is the error I happen to get:
??? Error using ==> mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.
Error in ==> sym.sym>sym.subsref at 1366
B = mupadmex(‘mllib::subsref’,A.s,inds{:});
Error in ==> NewtonMethosNonLinear at 5
f1 = 4*x(1)-x(2)+x(3)-x(1)*x(4);
I would appreciate some explanation on this since I don’t know how to move next. Thank you. Hi All. I am fairly new to Matlab and still learning. I am wondering if one may explain to me how I should enter a system of non-linear equations. For instance the equations I have are: 4*x(1)-x(2)+x(3)-x(1)*x(4) = 0; -x(1)+3*x(2)-2*x(3)-x(2)*x(4) = 0; and x(1)^2+x(2)^2+x(3)^2-1 = 0. Basically I want to enter the equations and use the Newton Method to solve using the Jacobian Matrix. This is how I enetered them in Matlab:
clear all
clc
syms x
f1 = 4*x(1)-x(2)+x(3)-x(1)*x(4);
f2 = -x(1)+3*x(2)-2*x(3)-x(2)*x(4);
f3 = x(1)^2+x(2)^2+x(3)^2-1;
F = [f1;f2;f3];
If I tell the program to run at this point, this is the error I happen to get:
??? Error using ==> mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.
Error in ==> sym.sym>sym.subsref at 1366
B = mupadmex(‘mllib::subsref’,A.s,inds{:});
Error in ==> NewtonMethosNonLinear at 5
f1 = 4*x(1)-x(2)+x(3)-x(1)*x(4);
I would appreciate some explanation on this since I don’t know how to move next. Thank you. jacob shila MATLAB Answers — New Questions
Is it possible to change some parameters during a RL training?
Hello everyone,
For those who don’t know, I am currently working on a supervised learning/RL learning training session with a 3DOF model of a jet aircraft.
My idea is to change, during a training, some parameters such as the number of allowed interventions of the external controller as well as their duration. Another whish is to change accordingly these parametes as the agent makes progress, e.g. its episode reward will increase during training. Is it possible to do this during a training? That is, is it possible to implement some for loops that exploits the trainStats object while the training is runnig? Thank youHello everyone,
For those who don’t know, I am currently working on a supervised learning/RL learning training session with a 3DOF model of a jet aircraft.
My idea is to change, during a training, some parameters such as the number of allowed interventions of the external controller as well as their duration. Another whish is to change accordingly these parametes as the agent makes progress, e.g. its episode reward will increase during training. Is it possible to do this during a training? That is, is it possible to implement some for loops that exploits the trainStats object while the training is runnig? Thank you Hello everyone,
For those who don’t know, I am currently working on a supervised learning/RL learning training session with a 3DOF model of a jet aircraft.
My idea is to change, during a training, some parameters such as the number of allowed interventions of the external controller as well as their duration. Another whish is to change accordingly these parametes as the agent makes progress, e.g. its episode reward will increase during training. Is it possible to do this during a training? That is, is it possible to implement some for loops that exploits the trainStats object while the training is runnig? Thank you reinforcement learning, supervised learning, machine learning, rl, rl block, trainstats, matlab, simulink MATLAB Answers — New Questions
The input format when setting the prismatic joint input options to motion/provided by input
"I understand that when the prismatic joint input is set to motion/provided by input, the position, velocity, and acceleration values are required. However, I am unsure of the exact usage examples in this case. Could someone please provide some clarification?""I understand that when the prismatic joint input is set to motion/provided by input, the position, velocity, and acceleration values are required. However, I am unsure of the exact usage examples in this case. Could someone please provide some clarification?" "I understand that when the prismatic joint input is set to motion/provided by input, the position, velocity, and acceleration values are required. However, I am unsure of the exact usage examples in this case. Could someone please provide some clarification?" simulink, simscape MATLAB Answers — New Questions
simulink matlab function block
what function should I write in Simulink matlab function block so it generates square pulses as pulse generator , please helpwhat function should I write in Simulink matlab function block so it generates square pulses as pulse generator , please help what function should I write in Simulink matlab function block so it generates square pulses as pulse generator , please help simulink, matlab function MATLAB Answers — New Questions
Removing drift from EMG signal
i want to remove the drift from my emg signal that i obtained. i am using the following script
the original emg looks like this:
with the scipt above i get the following detrend:
u can see that the drift isnt completely removed, can anyone see what i am doing wrong or what i can change in my script to get the perfect result around y=0
thanks in advance!i want to remove the drift from my emg signal that i obtained. i am using the following script
the original emg looks like this:
with the scipt above i get the following detrend:
u can see that the drift isnt completely removed, can anyone see what i am doing wrong or what i can change in my script to get the perfect result around y=0
thanks in advance! i want to remove the drift from my emg signal that i obtained. i am using the following script
the original emg looks like this:
with the scipt above i get the following detrend:
u can see that the drift isnt completely removed, can anyone see what i am doing wrong or what i can change in my script to get the perfect result around y=0
thanks in advance! removing drift MATLAB Answers — New Questions
Error using trainNetwork (line 191) Too many input arguments.
Hello, i am trying to code an automatic detection of alzheimer from EEG signals but my code has an error when using trainNetwork. It worked perfectely with a SVM but doesn’t with a CNN. I tried looking online but nothing seems too work. I got this error :
Error using trainNetwork (line 191)
Too many input arguments.
Error in CNN (line 178)
net = trainNetwork(X_train, y_train, layers, options);
Caused by:
Error using gather
Too many input arguments.
Does anyone have an idea. Here is the part of my code that produce the CNN :
X = all_features{:, 1:end-1}; % Use parentheses () for table indexing
y = all_features.Label;
y = categorical(y);
disp([‘Feature matrix dimensions: ‘, num2str(size(X))]);
disp([‘Labels vector dimensions: ‘, num2str(size(y))]);
X = zscore(X);
numFeatures = size(X, 2);
numObservations = size(X, 1);
X = reshape(X, [numObservations, numFeatures, 1, 1]); % Reshape for CNN
layers = [
imageInputLayer([numFeatures 1 1])
convolution2dLayer([3 1], 8, ‘Padding’, ‘same’)
batchNormalizationLayer
reluLayer
maxPooling2dLayer([2 1], ‘Stride’, 2)
convolution2dLayer([3 1], 16, ‘Padding’, ‘same’)
batchNormalizationLayer
reluLayer
fullyConnectedLayer(2)
softmaxLayer
classificationLayer];
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 30, …
‘MiniBatchSize’, 16, …
‘InitialLearnRate’, 0.001, …
‘ValidationFrequency’, 10, …
‘Verbose’, false, …
‘Plots’, ‘training-progress’);
% 5-Fold Cross-Validation
cv = cvpartition(y, ‘KFold’, 5, ‘Stratify’, true);
accuracies = zeros(cv.NumTestSets, 1);
confusion_matrices = cell(cv.NumTestSets, 1);
for k = 1:cv.NumTestSets
train_idx = training(cv, k);
test_idx = test(cv, k);
X_train = X(train_idx, :, :, :);
y_train = y(train_idx);
X_test = X(test_idx, :, :, :);
y_test = y(test_idx);
net = trainNetwork(X_train, y_train, layers, options);
y_pred = classify(net, X_test);
confusion_matrices{k} = confusionmat(y_test, y_pred);
cm = confusion_matrices{k};
accuracies(k) = sum(diag(cm)) / sum(cm(:));
end
mean_accuracy = mean(accuracies);
fprintf(‘Mean Accuracy across 5 folds: %.2f%%n’, mean_accuracy * 100);
save(‘eeg_cnn_classifier_cv.mat’, ‘net’);
disp(‘Confusion Matrices for each fold:’);
for k = 1:cv.NumTestSets
disp([‘Fold ‘, num2str(k), ‘:’]);
disp(confusion_matrices{k});
endHello, i am trying to code an automatic detection of alzheimer from EEG signals but my code has an error when using trainNetwork. It worked perfectely with a SVM but doesn’t with a CNN. I tried looking online but nothing seems too work. I got this error :
Error using trainNetwork (line 191)
Too many input arguments.
Error in CNN (line 178)
net = trainNetwork(X_train, y_train, layers, options);
Caused by:
Error using gather
Too many input arguments.
Does anyone have an idea. Here is the part of my code that produce the CNN :
X = all_features{:, 1:end-1}; % Use parentheses () for table indexing
y = all_features.Label;
y = categorical(y);
disp([‘Feature matrix dimensions: ‘, num2str(size(X))]);
disp([‘Labels vector dimensions: ‘, num2str(size(y))]);
X = zscore(X);
numFeatures = size(X, 2);
numObservations = size(X, 1);
X = reshape(X, [numObservations, numFeatures, 1, 1]); % Reshape for CNN
layers = [
imageInputLayer([numFeatures 1 1])
convolution2dLayer([3 1], 8, ‘Padding’, ‘same’)
batchNormalizationLayer
reluLayer
maxPooling2dLayer([2 1], ‘Stride’, 2)
convolution2dLayer([3 1], 16, ‘Padding’, ‘same’)
batchNormalizationLayer
reluLayer
fullyConnectedLayer(2)
softmaxLayer
classificationLayer];
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 30, …
‘MiniBatchSize’, 16, …
‘InitialLearnRate’, 0.001, …
‘ValidationFrequency’, 10, …
‘Verbose’, false, …
‘Plots’, ‘training-progress’);
% 5-Fold Cross-Validation
cv = cvpartition(y, ‘KFold’, 5, ‘Stratify’, true);
accuracies = zeros(cv.NumTestSets, 1);
confusion_matrices = cell(cv.NumTestSets, 1);
for k = 1:cv.NumTestSets
train_idx = training(cv, k);
test_idx = test(cv, k);
X_train = X(train_idx, :, :, :);
y_train = y(train_idx);
X_test = X(test_idx, :, :, :);
y_test = y(test_idx);
net = trainNetwork(X_train, y_train, layers, options);
y_pred = classify(net, X_test);
confusion_matrices{k} = confusionmat(y_test, y_pred);
cm = confusion_matrices{k};
accuracies(k) = sum(diag(cm)) / sum(cm(:));
end
mean_accuracy = mean(accuracies);
fprintf(‘Mean Accuracy across 5 folds: %.2f%%n’, mean_accuracy * 100);
save(‘eeg_cnn_classifier_cv.mat’, ‘net’);
disp(‘Confusion Matrices for each fold:’);
for k = 1:cv.NumTestSets
disp([‘Fold ‘, num2str(k), ‘:’]);
disp(confusion_matrices{k});
end Hello, i am trying to code an automatic detection of alzheimer from EEG signals but my code has an error when using trainNetwork. It worked perfectely with a SVM but doesn’t with a CNN. I tried looking online but nothing seems too work. I got this error :
Error using trainNetwork (line 191)
Too many input arguments.
Error in CNN (line 178)
net = trainNetwork(X_train, y_train, layers, options);
Caused by:
Error using gather
Too many input arguments.
Does anyone have an idea. Here is the part of my code that produce the CNN :
X = all_features{:, 1:end-1}; % Use parentheses () for table indexing
y = all_features.Label;
y = categorical(y);
disp([‘Feature matrix dimensions: ‘, num2str(size(X))]);
disp([‘Labels vector dimensions: ‘, num2str(size(y))]);
X = zscore(X);
numFeatures = size(X, 2);
numObservations = size(X, 1);
X = reshape(X, [numObservations, numFeatures, 1, 1]); % Reshape for CNN
layers = [
imageInputLayer([numFeatures 1 1])
convolution2dLayer([3 1], 8, ‘Padding’, ‘same’)
batchNormalizationLayer
reluLayer
maxPooling2dLayer([2 1], ‘Stride’, 2)
convolution2dLayer([3 1], 16, ‘Padding’, ‘same’)
batchNormalizationLayer
reluLayer
fullyConnectedLayer(2)
softmaxLayer
classificationLayer];
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 30, …
‘MiniBatchSize’, 16, …
‘InitialLearnRate’, 0.001, …
‘ValidationFrequency’, 10, …
‘Verbose’, false, …
‘Plots’, ‘training-progress’);
% 5-Fold Cross-Validation
cv = cvpartition(y, ‘KFold’, 5, ‘Stratify’, true);
accuracies = zeros(cv.NumTestSets, 1);
confusion_matrices = cell(cv.NumTestSets, 1);
for k = 1:cv.NumTestSets
train_idx = training(cv, k);
test_idx = test(cv, k);
X_train = X(train_idx, :, :, :);
y_train = y(train_idx);
X_test = X(test_idx, :, :, :);
y_test = y(test_idx);
net = trainNetwork(X_train, y_train, layers, options);
y_pred = classify(net, X_test);
confusion_matrices{k} = confusionmat(y_test, y_pred);
cm = confusion_matrices{k};
accuracies(k) = sum(diag(cm)) / sum(cm(:));
end
mean_accuracy = mean(accuracies);
fprintf(‘Mean Accuracy across 5 folds: %.2f%%n’, mean_accuracy * 100);
save(‘eeg_cnn_classifier_cv.mat’, ‘net’);
disp(‘Confusion Matrices for each fold:’);
for k = 1:cv.NumTestSets
disp([‘Fold ‘, num2str(k), ‘:’]);
disp(confusion_matrices{k});
end cnn, machine learning, deep learning MATLAB Answers — New Questions
How to average the columns within this cell array?
Hi, I have a deeply nested cell array of cells which contains a lot of doubles (C_512_eye_numeric). I am aiming to average the columns of the doubles column-wise. I cant seem to achieve this.
Can someone help?
Thanks!Hi, I have a deeply nested cell array of cells which contains a lot of doubles (C_512_eye_numeric). I am aiming to average the columns of the doubles column-wise. I cant seem to achieve this.
Can someone help?
Thanks! Hi, I have a deeply nested cell array of cells which contains a lot of doubles (C_512_eye_numeric). I am aiming to average the columns of the doubles column-wise. I cant seem to achieve this.
Can someone help?
Thanks! cell, cell array, doubles, matrix, average MATLAB Answers — New Questions
How to save a variable from workspace into a .mat file, but the variable obtains value from a for loop?
I have this code and i want to save the variable x from workspace into a file clc;
clear;
close all;
% Parameters
sampling_frequency = 1000; % Sampling frequency in Hz
duration = 5; % Duration of signal acquisition in seconds
num_samples = sampling_frequency * duration;
% Initialize variables
time = (0:num_samples-1) / sampling_frequency;
x = zeros(1, num_samples);
% Connect to Arduino
a = arduino();
% Bandpass filter parameters
low_cutoff_frequency = 6; % Low cutoff frequency in Hz
high_cutoff_frequency = 400; % High cutoff frequency in Hz
% Design the bandpass filter
[b, a_filter] = butter(2, [low_cutoff_frequency, high_cutoff_frequency] / (sampling_frequency / 2), ‘bandpass’); %Normalized between [0 1]
% Plot for real-time visualization of raw signal
figure(‘Name’, ‘Real-Time Raw EMG Signal’);
h_raw = plot(nan, nan); % Initialize plot with NaN
grid on;
title(‘Real-Time Raw EMG Signal’);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Plot for real-time visualization of filtered signal
figure(‘Name’, ‘Real-Time Filtered EMG Signal’);
h_filtered = plot(nan, nan); % Initialize plot with NaN
grid on;
title(‘Real-Time Filtered EMG Signal’);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Start loop to acquire signal
for i = 1:num_samples
% Read voltage
raw_voltage = readVoltage(a, ‘A0’);
% Store raw voltage
x(i) = raw_voltage;
% Apply bandpass filter to the signal up to current point if enough data points are collected
if i >= 25
filtered_signal = filtfilt(b, a_filter, x(1:i));
% Remove DC offset by subtracting the mean of the filtered signal
filtered_signal = filtered_signal – mean(filtered_signal);
% Update plot for filtered signal
set(h_filtered, ‘YData’, filtered_signal, ‘XData’, time(1:i));
end
% Update plot for raw signal
set(h_raw, ‘YData’, x(1:i), ‘XData’, time(1:i));
drawnow;
end
save(‘EMG_data.mat’, ‘x’,);
It doesn’t create the .mat file and I suppose the problem is that i stop the iteration very early. But I want to save any values that are obtained until any iteration. How can I fix that?I have this code and i want to save the variable x from workspace into a file clc;
clear;
close all;
% Parameters
sampling_frequency = 1000; % Sampling frequency in Hz
duration = 5; % Duration of signal acquisition in seconds
num_samples = sampling_frequency * duration;
% Initialize variables
time = (0:num_samples-1) / sampling_frequency;
x = zeros(1, num_samples);
% Connect to Arduino
a = arduino();
% Bandpass filter parameters
low_cutoff_frequency = 6; % Low cutoff frequency in Hz
high_cutoff_frequency = 400; % High cutoff frequency in Hz
% Design the bandpass filter
[b, a_filter] = butter(2, [low_cutoff_frequency, high_cutoff_frequency] / (sampling_frequency / 2), ‘bandpass’); %Normalized between [0 1]
% Plot for real-time visualization of raw signal
figure(‘Name’, ‘Real-Time Raw EMG Signal’);
h_raw = plot(nan, nan); % Initialize plot with NaN
grid on;
title(‘Real-Time Raw EMG Signal’);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Plot for real-time visualization of filtered signal
figure(‘Name’, ‘Real-Time Filtered EMG Signal’);
h_filtered = plot(nan, nan); % Initialize plot with NaN
grid on;
title(‘Real-Time Filtered EMG Signal’);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Start loop to acquire signal
for i = 1:num_samples
% Read voltage
raw_voltage = readVoltage(a, ‘A0’);
% Store raw voltage
x(i) = raw_voltage;
% Apply bandpass filter to the signal up to current point if enough data points are collected
if i >= 25
filtered_signal = filtfilt(b, a_filter, x(1:i));
% Remove DC offset by subtracting the mean of the filtered signal
filtered_signal = filtered_signal – mean(filtered_signal);
% Update plot for filtered signal
set(h_filtered, ‘YData’, filtered_signal, ‘XData’, time(1:i));
end
% Update plot for raw signal
set(h_raw, ‘YData’, x(1:i), ‘XData’, time(1:i));
drawnow;
end
save(‘EMG_data.mat’, ‘x’,);
It doesn’t create the .mat file and I suppose the problem is that i stop the iteration very early. But I want to save any values that are obtained until any iteration. How can I fix that? I have this code and i want to save the variable x from workspace into a file clc;
clear;
close all;
% Parameters
sampling_frequency = 1000; % Sampling frequency in Hz
duration = 5; % Duration of signal acquisition in seconds
num_samples = sampling_frequency * duration;
% Initialize variables
time = (0:num_samples-1) / sampling_frequency;
x = zeros(1, num_samples);
% Connect to Arduino
a = arduino();
% Bandpass filter parameters
low_cutoff_frequency = 6; % Low cutoff frequency in Hz
high_cutoff_frequency = 400; % High cutoff frequency in Hz
% Design the bandpass filter
[b, a_filter] = butter(2, [low_cutoff_frequency, high_cutoff_frequency] / (sampling_frequency / 2), ‘bandpass’); %Normalized between [0 1]
% Plot for real-time visualization of raw signal
figure(‘Name’, ‘Real-Time Raw EMG Signal’);
h_raw = plot(nan, nan); % Initialize plot with NaN
grid on;
title(‘Real-Time Raw EMG Signal’);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Plot for real-time visualization of filtered signal
figure(‘Name’, ‘Real-Time Filtered EMG Signal’);
h_filtered = plot(nan, nan); % Initialize plot with NaN
grid on;
title(‘Real-Time Filtered EMG Signal’);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Start loop to acquire signal
for i = 1:num_samples
% Read voltage
raw_voltage = readVoltage(a, ‘A0’);
% Store raw voltage
x(i) = raw_voltage;
% Apply bandpass filter to the signal up to current point if enough data points are collected
if i >= 25
filtered_signal = filtfilt(b, a_filter, x(1:i));
% Remove DC offset by subtracting the mean of the filtered signal
filtered_signal = filtered_signal – mean(filtered_signal);
% Update plot for filtered signal
set(h_filtered, ‘YData’, filtered_signal, ‘XData’, time(1:i));
end
% Update plot for raw signal
set(h_raw, ‘YData’, x(1:i), ‘XData’, time(1:i));
drawnow;
end
save(‘EMG_data.mat’, ‘x’,);
It doesn’t create the .mat file and I suppose the problem is that i stop the iteration very early. But I want to save any values that are obtained until any iteration. How can I fix that? save variable from workspace, iterations MATLAB Answers — New Questions
Correcting the error in Alamouti code (2 x 1)
I trying to code Alamouti code for BPSK in Rayleigh fading channel for BER simulation.There is a matrix dimention mismatch in decode section.I tried to correct it ,but it did not work.
Need your help to correct it.Thank you
clear all;
close all;
clc;
Ps = 1;%Transmit power
N = 10^6; % number of bits or symbols
NR = 1;
num_runs = 10;
snr_dB = -3:10 ; % in dB
rand(‘seed’,1); % initializing the rand() function so that random bits produced are same in every simulation
randn(‘seed’,1);
% Transmitter
x_data1 = rand(1,N/2)>0.5;
x_data2 = rand(1,N/2)>0.5;
binaryData = [x_data1; x_data2];
BPSK_data1 = 2*x_data1 – 1;
BPSK_data2 = 2*x_data2 – 1;
% BPSK modulation – 2×500000 matrix
BPSK_data =[BPSK_data1; BPSK_data2];
n1 = AWGN(1);
n2 = AWGN(1);
h1 = Rayleigh(1);
h2 = Rayleigh(1);
SNR = 10.^(snr_dB/10);
Noise_power = zeros(1,length(snr_dB));
for k = 1:length(snr_dB)
% Add complex AWGN noise power
Noise_power = Ps./SNR(k);
% In the first time slot, the received signal
y1 = h1.*BPSK_data1 + h2.*BPSK_data2 + n1;
% In the first time slot, the received signal
y2 = h1.*(-conj(BPSK_data2)) + h2.*(conj(BPSK_data1)) + n2;
%Rayleigh fading channel – 2×1 matrix
H = [h1 h2 ; conj(h2) -conj(h1)];
%Decode the sysmbols – ZF decoder
x1_hat = pinv(H).*y1;
x2_hat = pinv(H).*conj(y2);
rx_bits = [x1_hat;x2_hat];
rx_bits = real(rx_bits) > 0;
% Count errors
nErr(k) = size(find(binaryData – rx_bits),1);
end
% counting the errors
ber = nErr/N; % simulated ber
figure(1);
semilogy(snr_dB,ber,’b.-‘);
% axis([0 10 10^-4 0.6])
grid on;
legend( ‘MIMO – BER’);
xlabel(‘SNR[dB]’);
ylabel(‘Bit Error Rate’);
title(‘BER for MIMO-BPSK’);
%%%%% AWGN noise %%%%%
function n = AWGN(N)
n = rand(1,N);
end
%%%%% Rayleigh channel %%%%%%
function h = Rayleigh(N);
x = sqrt(1/2).*rand(1,N);
y = sqrt(1/2).*rand(1,N);
h = abs(x + i*y);
endI trying to code Alamouti code for BPSK in Rayleigh fading channel for BER simulation.There is a matrix dimention mismatch in decode section.I tried to correct it ,but it did not work.
Need your help to correct it.Thank you
clear all;
close all;
clc;
Ps = 1;%Transmit power
N = 10^6; % number of bits or symbols
NR = 1;
num_runs = 10;
snr_dB = -3:10 ; % in dB
rand(‘seed’,1); % initializing the rand() function so that random bits produced are same in every simulation
randn(‘seed’,1);
% Transmitter
x_data1 = rand(1,N/2)>0.5;
x_data2 = rand(1,N/2)>0.5;
binaryData = [x_data1; x_data2];
BPSK_data1 = 2*x_data1 – 1;
BPSK_data2 = 2*x_data2 – 1;
% BPSK modulation – 2×500000 matrix
BPSK_data =[BPSK_data1; BPSK_data2];
n1 = AWGN(1);
n2 = AWGN(1);
h1 = Rayleigh(1);
h2 = Rayleigh(1);
SNR = 10.^(snr_dB/10);
Noise_power = zeros(1,length(snr_dB));
for k = 1:length(snr_dB)
% Add complex AWGN noise power
Noise_power = Ps./SNR(k);
% In the first time slot, the received signal
y1 = h1.*BPSK_data1 + h2.*BPSK_data2 + n1;
% In the first time slot, the received signal
y2 = h1.*(-conj(BPSK_data2)) + h2.*(conj(BPSK_data1)) + n2;
%Rayleigh fading channel – 2×1 matrix
H = [h1 h2 ; conj(h2) -conj(h1)];
%Decode the sysmbols – ZF decoder
x1_hat = pinv(H).*y1;
x2_hat = pinv(H).*conj(y2);
rx_bits = [x1_hat;x2_hat];
rx_bits = real(rx_bits) > 0;
% Count errors
nErr(k) = size(find(binaryData – rx_bits),1);
end
% counting the errors
ber = nErr/N; % simulated ber
figure(1);
semilogy(snr_dB,ber,’b.-‘);
% axis([0 10 10^-4 0.6])
grid on;
legend( ‘MIMO – BER’);
xlabel(‘SNR[dB]’);
ylabel(‘Bit Error Rate’);
title(‘BER for MIMO-BPSK’);
%%%%% AWGN noise %%%%%
function n = AWGN(N)
n = rand(1,N);
end
%%%%% Rayleigh channel %%%%%%
function h = Rayleigh(N);
x = sqrt(1/2).*rand(1,N);
y = sqrt(1/2).*rand(1,N);
h = abs(x + i*y);
end I trying to code Alamouti code for BPSK in Rayleigh fading channel for BER simulation.There is a matrix dimention mismatch in decode section.I tried to correct it ,but it did not work.
Need your help to correct it.Thank you
clear all;
close all;
clc;
Ps = 1;%Transmit power
N = 10^6; % number of bits or symbols
NR = 1;
num_runs = 10;
snr_dB = -3:10 ; % in dB
rand(‘seed’,1); % initializing the rand() function so that random bits produced are same in every simulation
randn(‘seed’,1);
% Transmitter
x_data1 = rand(1,N/2)>0.5;
x_data2 = rand(1,N/2)>0.5;
binaryData = [x_data1; x_data2];
BPSK_data1 = 2*x_data1 – 1;
BPSK_data2 = 2*x_data2 – 1;
% BPSK modulation – 2×500000 matrix
BPSK_data =[BPSK_data1; BPSK_data2];
n1 = AWGN(1);
n2 = AWGN(1);
h1 = Rayleigh(1);
h2 = Rayleigh(1);
SNR = 10.^(snr_dB/10);
Noise_power = zeros(1,length(snr_dB));
for k = 1:length(snr_dB)
% Add complex AWGN noise power
Noise_power = Ps./SNR(k);
% In the first time slot, the received signal
y1 = h1.*BPSK_data1 + h2.*BPSK_data2 + n1;
% In the first time slot, the received signal
y2 = h1.*(-conj(BPSK_data2)) + h2.*(conj(BPSK_data1)) + n2;
%Rayleigh fading channel – 2×1 matrix
H = [h1 h2 ; conj(h2) -conj(h1)];
%Decode the sysmbols – ZF decoder
x1_hat = pinv(H).*y1;
x2_hat = pinv(H).*conj(y2);
rx_bits = [x1_hat;x2_hat];
rx_bits = real(rx_bits) > 0;
% Count errors
nErr(k) = size(find(binaryData – rx_bits),1);
end
% counting the errors
ber = nErr/N; % simulated ber
figure(1);
semilogy(snr_dB,ber,’b.-‘);
% axis([0 10 10^-4 0.6])
grid on;
legend( ‘MIMO – BER’);
xlabel(‘SNR[dB]’);
ylabel(‘Bit Error Rate’);
title(‘BER for MIMO-BPSK’);
%%%%% AWGN noise %%%%%
function n = AWGN(N)
n = rand(1,N);
end
%%%%% Rayleigh channel %%%%%%
function h = Rayleigh(N);
x = sqrt(1/2).*rand(1,N);
y = sqrt(1/2).*rand(1,N);
h = abs(x + i*y);
end matlab, mimo, wireless, alamouti code MATLAB Answers — New Questions
how to make task in simulink
I’m trying to create a motor control simulation.
I would like to implement functions according to the execution cycle as if configuring actual motor control embedded software.
For example, I want to configure the current control subsystem so that this subsystem runs at a 1ms task, and the speed control subsystem calculates at a 5ms task.
How can I use Simulink to implement something like the example?I’m trying to create a motor control simulation.
I would like to implement functions according to the execution cycle as if configuring actual motor control embedded software.
For example, I want to configure the current control subsystem so that this subsystem runs at a 1ms task, and the speed control subsystem calculates at a 5ms task.
How can I use Simulink to implement something like the example? I’m trying to create a motor control simulation.
I would like to implement functions according to the execution cycle as if configuring actual motor control embedded software.
For example, I want to configure the current control subsystem so that this subsystem runs at a 1ms task, and the speed control subsystem calculates at a 5ms task.
How can I use Simulink to implement something like the example? simulink, task MATLAB Answers — New Questions
I am unable to connect MQTT client using Thingspeak in MATLAB.
Here is my piece of code, I am following the steps of the tutorial https://www.mathworks.com/help/icomm/ug/get-started-with-mqtt.html
clientID = "client id";
userName = "user name";
password = "password";
rootCert = "Path";
brokerAddress = "ssl://mqtt3.thingspeak.com";
port = 8883;
mqClient = mqttclient(brokerAddress, Port = port, ClientID = clientID,…
Username = userName, Password = password, CARootCertificate = rootCert);
upon reaching the mqClient, the following error occurs
ThingSpeakMQTT
Error: File: ThingSpeakMQTT.m
Incorrect use of ‘=’ operator. To assign a value to a variable, use ‘=’.
To compare values for equality, use ‘==’.
Please someone guide me on this.Here is my piece of code, I am following the steps of the tutorial https://www.mathworks.com/help/icomm/ug/get-started-with-mqtt.html
clientID = "client id";
userName = "user name";
password = "password";
rootCert = "Path";
brokerAddress = "ssl://mqtt3.thingspeak.com";
port = 8883;
mqClient = mqttclient(brokerAddress, Port = port, ClientID = clientID,…
Username = userName, Password = password, CARootCertificate = rootCert);
upon reaching the mqClient, the following error occurs
ThingSpeakMQTT
Error: File: ThingSpeakMQTT.m
Incorrect use of ‘=’ operator. To assign a value to a variable, use ‘=’.
To compare values for equality, use ‘==’.
Please someone guide me on this. Here is my piece of code, I am following the steps of the tutorial https://www.mathworks.com/help/icomm/ug/get-started-with-mqtt.html
clientID = "client id";
userName = "user name";
password = "password";
rootCert = "Path";
brokerAddress = "ssl://mqtt3.thingspeak.com";
port = 8883;
mqClient = mqttclient(brokerAddress, Port = port, ClientID = clientID,…
Username = userName, Password = password, CARootCertificate = rootCert);
upon reaching the mqClient, the following error occurs
ThingSpeakMQTT
Error: File: ThingSpeakMQTT.m
Incorrect use of ‘=’ operator. To assign a value to a variable, use ‘=’.
To compare values for equality, use ‘==’.
Please someone guide me on this. thingspeak, mqtt MATLAB Answers — New Questions
MEX functions work fine on R2017a but not on R2021b even after successful recompilation on R2021b
Hello, here is my problem: I upgraded from Matlab R2017a to 2021b based on the recommendation for compatibility with Windows 11 (I moved to a new PC). However, I am experiencing problems with the MEX functions I use to connect to hardware (open connexion, close connexion, update status, basic functions). I recompiled the MEX functions (for which I have all the source files) under MATLAB 2021b, using both the -R2017b and -R2018a options, and they recompiled successfully. Despite this, I cannot connect to the hardware. If I use the same MEX functions on the same computer (Windows 11) with MATLAB R2017a, it works fine (not if I compiled the MEX with -R2018a option which makes sense I believe). Additionally, I am using external software from the manufacturer to control the hardware, and it works fine too (driver correctly installed). The issue only occurs with MATLAB 2021b. I compared the verbose outputs of the MEX function compilations with the -R2017b and -R2018a options and found no significant differences. I am confused as to why the MEX functions work with MATLAB R2017a but not with R2021b on the same computer, especially since the functions recompiled with R2021b show no warnings or errors. Do you have any tips or ideas to solve this issue?
Additionnaly, the MEX functions works fine with R2017a, hardware controlled correctly, while with R2021b error code from MEX functions states "device not found". Matlab configuration between installation R2017a and R2021b is the same (paths, compiler, etc.). Thanks !Hello, here is my problem: I upgraded from Matlab R2017a to 2021b based on the recommendation for compatibility with Windows 11 (I moved to a new PC). However, I am experiencing problems with the MEX functions I use to connect to hardware (open connexion, close connexion, update status, basic functions). I recompiled the MEX functions (for which I have all the source files) under MATLAB 2021b, using both the -R2017b and -R2018a options, and they recompiled successfully. Despite this, I cannot connect to the hardware. If I use the same MEX functions on the same computer (Windows 11) with MATLAB R2017a, it works fine (not if I compiled the MEX with -R2018a option which makes sense I believe). Additionally, I am using external software from the manufacturer to control the hardware, and it works fine too (driver correctly installed). The issue only occurs with MATLAB 2021b. I compared the verbose outputs of the MEX function compilations with the -R2017b and -R2018a options and found no significant differences. I am confused as to why the MEX functions work with MATLAB R2017a but not with R2021b on the same computer, especially since the functions recompiled with R2021b show no warnings or errors. Do you have any tips or ideas to solve this issue?
Additionnaly, the MEX functions works fine with R2017a, hardware controlled correctly, while with R2021b error code from MEX functions states "device not found". Matlab configuration between installation R2017a and R2021b is the same (paths, compiler, etc.). Thanks ! Hello, here is my problem: I upgraded from Matlab R2017a to 2021b based on the recommendation for compatibility with Windows 11 (I moved to a new PC). However, I am experiencing problems with the MEX functions I use to connect to hardware (open connexion, close connexion, update status, basic functions). I recompiled the MEX functions (for which I have all the source files) under MATLAB 2021b, using both the -R2017b and -R2018a options, and they recompiled successfully. Despite this, I cannot connect to the hardware. If I use the same MEX functions on the same computer (Windows 11) with MATLAB R2017a, it works fine (not if I compiled the MEX with -R2018a option which makes sense I believe). Additionally, I am using external software from the manufacturer to control the hardware, and it works fine too (driver correctly installed). The issue only occurs with MATLAB 2021b. I compared the verbose outputs of the MEX function compilations with the -R2017b and -R2018a options and found no significant differences. I am confused as to why the MEX functions work with MATLAB R2017a but not with R2021b on the same computer, especially since the functions recompiled with R2021b show no warnings or errors. Do you have any tips or ideas to solve this issue?
Additionnaly, the MEX functions works fine with R2017a, hardware controlled correctly, while with R2021b error code from MEX functions states "device not found". Matlab configuration between installation R2017a and R2021b is the same (paths, compiler, etc.). Thanks ! function, matlab function, mex MATLAB Answers — New Questions
solving this maximization problem
Hi everyone,
Could anyone assist me with solving this maximization problem in MATLAB? I need to maximize the following function and determine the optimal values of r and t.
Thank you!
-(1/((1 + 2 a)^2))
t (-3 – 2 r + t – 5 a + 2 t a +
2 Sqrt[2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)] +
2 a Sqrt[
2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]) (-4 r +
2 a (-2 + Sqrt[
2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]) +
3 (-1 + Sqrt[2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]))Hi everyone,
Could anyone assist me with solving this maximization problem in MATLAB? I need to maximize the following function and determine the optimal values of r and t.
Thank you!
-(1/((1 + 2 a)^2))
t (-3 – 2 r + t – 5 a + 2 t a +
2 Sqrt[2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)] +
2 a Sqrt[
2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]) (-4 r +
2 a (-2 + Sqrt[
2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]) +
3 (-1 + Sqrt[2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)])) Hi everyone,
Could anyone assist me with solving this maximization problem in MATLAB? I need to maximize the following function and determine the optimal values of r and t.
Thank you!
-(1/((1 + 2 a)^2))
t (-3 – 2 r + t – 5 a + 2 t a +
2 Sqrt[2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)] +
2 a Sqrt[
2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]) (-4 r +
2 a (-2 + Sqrt[
2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)]) +
3 (-1 + Sqrt[2 (2 + r – t) + (-2 + 2 r^2 + t)/(1 + a)])) optimal, maximize MATLAB Answers — New Questions
How to convert sparse matrix into image?
I have a sparse matrix which contains
aa =
(1,1) 72
(1,2) 101
(1,3) 108
Now I want to convert this into image …?I have a sparse matrix which contains
aa =
(1,1) 72
(1,2) 101
(1,3) 108
Now I want to convert this into image …? I have a sparse matrix which contains
aa =
(1,1) 72
(1,2) 101
(1,3) 108
Now I want to convert this into image …? how to convert sparse matrix into image? MATLAB Answers — New Questions
Cannot append double array local function variable to an existing structured double
%My existing structure is a 103 X 4 double. I would like to add an additional column to make 103 x 5 double, by adding shoe size (column 5) to my curated list of store stock (103 X 4 table)
%shoe_size = (1,:) %column array calculated locally in function
newstruct = shoe_size
existing = userdata.shoe.brand;
values_cell = shoe_size;
for i = 1:numel(existing)
existing(i).(newstruct) = values_cell(i,5);
end%My existing structure is a 103 X 4 double. I would like to add an additional column to make 103 x 5 double, by adding shoe size (column 5) to my curated list of store stock (103 X 4 table)
%shoe_size = (1,:) %column array calculated locally in function
newstruct = shoe_size
existing = userdata.shoe.brand;
values_cell = shoe_size;
for i = 1:numel(existing)
existing(i).(newstruct) = values_cell(i,5);
end %My existing structure is a 103 X 4 double. I would like to add an additional column to make 103 x 5 double, by adding shoe size (column 5) to my curated list of store stock (103 X 4 table)
%shoe_size = (1,:) %column array calculated locally in function
newstruct = shoe_size
existing = userdata.shoe.brand;
values_cell = shoe_size;
for i = 1:numel(existing)
existing(i).(newstruct) = values_cell(i,5);
end structures, for loop, arrays MATLAB Answers — New Questions