Category: Matlab
Category Archives: Matlab
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
what(): Unable to launch the MATLABWindow application during installation
So, I’m running a fresh install of Manjaro Gnome and I’m trying to install matlab. I downloaded the installer, unpacked but when I try to run "bash ./install" it gives me the error:
terminate called after throwing an instance of ‘std::runtime_error’
what(): Unable to launch the MATLABWindow application
Matlab version is R2020a.So, I’m running a fresh install of Manjaro Gnome and I’m trying to install matlab. I downloaded the installer, unpacked but when I try to run "bash ./install" it gives me the error:
terminate called after throwing an instance of ‘std::runtime_error’
what(): Unable to launch the MATLABWindow application
Matlab version is R2020a. So, I’m running a fresh install of Manjaro Gnome and I’m trying to install matlab. I downloaded the installer, unpacked but when I try to run "bash ./install" it gives me the error:
terminate called after throwing an instance of ‘std::runtime_error’
what(): Unable to launch the MATLABWindow application
Matlab version is R2020a. manjaro archlinux runtime_error MATLAB Answers — New Questions
What mex compiler can I use on my Macbook Pro 2017?
I have some software which utilizes a couple mex functions, compiled from .c files. They were compiled on a windows computer and so only work on Windows. I’m updating the software to work on other platforms, so I need to re-compile the c files on my mac to make mex functions that are compatible with mac. To do this, I need a compiler that’s compatible with mac. As far as I can tell, the only compiler I can get for free is Xcode.
However, when I try to install Xcode, I can’t. It is not compatible with anything before MacOS 14. Yet when I try to download MacOS 14 Sonoma, I can’t because it’s not compatible with my computer, only with Macbook Pro 2018 and later.
So my question is, how can I compile .c files into mex functions on my macbook pro 2017? Is there any free compiler out there that will do the job?I have some software which utilizes a couple mex functions, compiled from .c files. They were compiled on a windows computer and so only work on Windows. I’m updating the software to work on other platforms, so I need to re-compile the c files on my mac to make mex functions that are compatible with mac. To do this, I need a compiler that’s compatible with mac. As far as I can tell, the only compiler I can get for free is Xcode.
However, when I try to install Xcode, I can’t. It is not compatible with anything before MacOS 14. Yet when I try to download MacOS 14 Sonoma, I can’t because it’s not compatible with my computer, only with Macbook Pro 2018 and later.
So my question is, how can I compile .c files into mex functions on my macbook pro 2017? Is there any free compiler out there that will do the job? I have some software which utilizes a couple mex functions, compiled from .c files. They were compiled on a windows computer and so only work on Windows. I’m updating the software to work on other platforms, so I need to re-compile the c files on my mac to make mex functions that are compatible with mac. To do this, I need a compiler that’s compatible with mac. As far as I can tell, the only compiler I can get for free is Xcode.
However, when I try to install Xcode, I can’t. It is not compatible with anything before MacOS 14. Yet when I try to download MacOS 14 Sonoma, I can’t because it’s not compatible with my computer, only with Macbook Pro 2018 and later.
So my question is, how can I compile .c files into mex functions on my macbook pro 2017? Is there any free compiler out there that will do the job? mex compiler, mex, mac, macbook pro 2017 MATLAB Answers — New Questions
Accurately obtaining the value of a variable at the requested points
Dear all
I am attaching a data set, where the first and second columns represent spatial coordinates (x,y) in two-dimensional space, while the third column shows the value of a given magnitude at the aforementioned set of (x,y) points. I was wondering which could be the best option in a scenario inside a for loop, where the (x,y) variables change at each step, to obtain an accurate value for the aforementioned variable defined in the third column of the attached file, even if for that combination of (x,y) coordinates the value of the variable is not present a priori. Would be something like
griddata(file(:,1),file(:,2),file(:,3),x,y,"cubic");
a quick and accurate approach?Dear all
I am attaching a data set, where the first and second columns represent spatial coordinates (x,y) in two-dimensional space, while the third column shows the value of a given magnitude at the aforementioned set of (x,y) points. I was wondering which could be the best option in a scenario inside a for loop, where the (x,y) variables change at each step, to obtain an accurate value for the aforementioned variable defined in the third column of the attached file, even if for that combination of (x,y) coordinates the value of the variable is not present a priori. Would be something like
griddata(file(:,1),file(:,2),file(:,3),x,y,"cubic");
a quick and accurate approach? Dear all
I am attaching a data set, where the first and second columns represent spatial coordinates (x,y) in two-dimensional space, while the third column shows the value of a given magnitude at the aforementioned set of (x,y) points. I was wondering which could be the best option in a scenario inside a for loop, where the (x,y) variables change at each step, to obtain an accurate value for the aforementioned variable defined in the third column of the attached file, even if for that combination of (x,y) coordinates the value of the variable is not present a priori. Would be something like
griddata(file(:,1),file(:,2),file(:,3),x,y,"cubic");
a quick and accurate approach? guessing data at a given set of points MATLAB Answers — New Questions
No puedo instalar matlab R2020a, me sale un error del uninstaller200_win65.zip
No puedo instalar el matlab, lo he intentado varias veces, pero siempre me salta el mismo error de que no encuentra el uninstaller200_win64.zipNo puedo instalar el matlab, lo he intentado varias veces, pero siempre me salta el mismo error de que no encuentra el uninstaller200_win64.zip No puedo instalar el matlab, lo he intentado varias veces, pero siempre me salta el mismo error de que no encuentra el uninstaller200_win64.zip error, installation, matlab MATLAB Answers — New Questions
double and triple integral for a complex function. I coded but did not get any output
f = (-1) * (x + l/2) ./ ((x + l/2).^2 + (y – y1).^2 + (z – z1).^2).^(3/2);
The goal is to do the double integral of that function over dy1 and dz1 and then the next step is to do the triple integral of the result(double integration result) over dx,dy and dz. I tried these in several ways but it looks like Matlab is unable to to this integration. Any suggestion?f = (-1) * (x + l/2) ./ ((x + l/2).^2 + (y – y1).^2 + (z – z1).^2).^(3/2);
The goal is to do the double integral of that function over dy1 and dz1 and then the next step is to do the triple integral of the result(double integration result) over dx,dy and dz. I tried these in several ways but it looks like Matlab is unable to to this integration. Any suggestion? f = (-1) * (x + l/2) ./ ((x + l/2).^2 + (y – y1).^2 + (z – z1).^2).^(3/2);
The goal is to do the double integral of that function over dy1 and dz1 and then the next step is to do the triple integral of the result(double integration result) over dx,dy and dz. I tried these in several ways but it looks like Matlab is unable to to this integration. Any suggestion? doble integration, matlab MATLAB Answers — New Questions
Changing sample time of multiple blocks at once
Hi, I have a subsystem with many many blocks and I want to change all their sample times from 1 to -1. I was wondering if there’s any shortcut to do this?Hi, I have a subsystem with many many blocks and I want to change all their sample times from 1 to -1. I was wondering if there’s any shortcut to do this? Hi, I have a subsystem with many many blocks and I want to change all their sample times from 1 to -1. I was wondering if there’s any shortcut to do this? simulink, sample time MATLAB Answers — New Questions
Matlab inherited environment when launched from command window
It has been my experience that Matlab inherits the dos environment when launched from a command window (or powershell).
e.g. open Command Prompt
c:UsersFoo> matlab
This does in fact work on 2 laptops Win10 and Win11. On a 3rd Win11 laptop however it does not seem to work. I did some workarounds within Matlab to get past that but I also found when I execute dos .bat from Matlab on that 3rd laptop, The dos window opened does not have the env from the original that I used to launch Matlab.
Is there a workaround? My searches came up dry.It has been my experience that Matlab inherits the dos environment when launched from a command window (or powershell).
e.g. open Command Prompt
c:UsersFoo> matlab
This does in fact work on 2 laptops Win10 and Win11. On a 3rd Win11 laptop however it does not seem to work. I did some workarounds within Matlab to get past that but I also found when I execute dos .bat from Matlab on that 3rd laptop, The dos window opened does not have the env from the original that I used to launch Matlab.
Is there a workaround? My searches came up dry. It has been my experience that Matlab inherits the dos environment when launched from a command window (or powershell).
e.g. open Command Prompt
c:UsersFoo> matlab
This does in fact work on 2 laptops Win10 and Win11. On a 3rd Win11 laptop however it does not seem to work. I did some workarounds within Matlab to get past that but I also found when I execute dos .bat from Matlab on that 3rd laptop, The dos window opened does not have the env from the original that I used to launch Matlab.
Is there a workaround? My searches came up dry. dos, environment, matlab MATLAB Answers — New Questions
How to creat grouped violin plot?
Hi, how can I create a grouped violin plot like this? I have tried different violin plot function such as GitHub – bastibe/Violinplot-Matlab: Violin Plots for Matlab. But I cannot find a way to create violin plot that is grouped by their categoery. The example figure is created in Seaborn-python. But I am not very familiar with python so I can only create the figure with default setting. It will be great if somebody can help me to create it in Matlab! :)Hi, how can I create a grouped violin plot like this? I have tried different violin plot function such as GitHub – bastibe/Violinplot-Matlab: Violin Plots for Matlab. But I cannot find a way to create violin plot that is grouped by their categoery. The example figure is created in Seaborn-python. But I am not very familiar with python so I can only create the figure with default setting. It will be great if somebody can help me to create it in Matlab! 🙂 Hi, how can I create a grouped violin plot like this? I have tried different violin plot function such as GitHub – bastibe/Violinplot-Matlab: Violin Plots for Matlab. But I cannot find a way to create violin plot that is grouped by their categoery. The example figure is created in Seaborn-python. But I am not very familiar with python so I can only create the figure with default setting. It will be great if somebody can help me to create it in Matlab! 🙂 violin plot, grouped by categoery MATLAB Answers — New Questions
ncorr post CS tool fail
Hi,
I have been doing research at UNSW in Australia. I have been using the ncorr in my research work for image processing. However, in the step of image processing, the ncorr_post CS tool is not working. Every time, it gives me the below error. Could you please let me know the reason of this problem and how to sort it this problem?Hi,
I have been doing research at UNSW in Australia. I have been using the ncorr in my research work for image processing. However, in the step of image processing, the ncorr_post CS tool is not working. Every time, it gives me the below error. Could you please let me know the reason of this problem and how to sort it this problem? Hi,
I have been doing research at UNSW in Australia. I have been using the ncorr in my research work for image processing. However, in the step of image processing, the ncorr_post CS tool is not working. Every time, it gives me the below error. Could you please let me know the reason of this problem and how to sort it this problem? ncorr, matlab MATLAB Answers — New Questions
Reaction wheel in SimMechanics
How to create a reaction relationship between two bodies in SimMechanics?
Task: transferring torque from a reaction wheel to the body it is attached to.
Problem: the wheel rotates, but the body does not move, the torque is not transferred.
Software used: transferring a model from SolidWorks to SimMechanics.How to create a reaction relationship between two bodies in SimMechanics?
Task: transferring torque from a reaction wheel to the body it is attached to.
Problem: the wheel rotates, but the body does not move, the torque is not transferred.
Software used: transferring a model from SolidWorks to SimMechanics. How to create a reaction relationship between two bodies in SimMechanics?
Task: transferring torque from a reaction wheel to the body it is attached to.
Problem: the wheel rotates, but the body does not move, the torque is not transferred.
Software used: transferring a model from SolidWorks to SimMechanics. simmechanics, solidworks, simulink MATLAB Answers — New Questions