Unable to perform assignment because the left and right sides have a different number of elements.

3 vues (au cours des 30 derniers jours)
I am getting that error when trying to run the code.
error: Unable to perform assignment because the left and right sides have a different number of elements.
Here is the code I am trying to run:
% Define the functions g1, g2, g3, g4
g1 = @(t) -5 * tri((2 - t) / 6);
g2 = @(t) 7 * tri(3 * t) - 4 * tri(t - 4);
g3 = @(t) tri(t + 2) - 4 * tri((t + 4) / 3);
g4 = @(t) -5 * tri(t) .* tri(t - 1/2);
% Define a range of time values
t_values = linspace(-10, 10, 1000);
% Initialize arrays to store results
nonzero_times = zeros(1, 4);
back_to_zero_times = zeros(1, 4);
max_values = zeros(1, 4);
min_values = zeros(1, 4);
% Calculate values for each function
for i = 1:4
% Find the first nonzero time
nonzero_indices = find(g1(t_values) ~= 0, 1);
nonzero_times(i) = t_values(nonzero_indices);
% Find the last time to go back to zero and stay there
nonzero_indices = find(g1(t_values) ~= 0);
back_to_zero_indices = find(g1(t_values(nonzero_indices)) == 0, 1, 'last');
back_to_zero_times(i) = t_values(nonzero_indices(back_to_zero_indices));
% Find the maximum value
max_values(i) = max(g1(t_values));
% Find the minimum value
min_values(i) = min(g1(t_values));
end
Unrecognized function or variable 'tri'.

Error in solution>@(t)-5*tri((2-t)/6) (line 2)
g1 = @(t) -5 * tri((2 - t) / 6);
% Display results
disp('Nonzero times:');
disp(nonzero_times);
disp('Back to zero and stay times:');
disp(back_to_zero_times);
disp('Maximum values:');
disp(max_values);
disp('Minimum values:');
disp(min_values);
  2 commentaires
Inmer Jimenez
Inmer Jimenez le 7 Mar 2024
Modifié(e) : Inmer Jimenez le 7 Mar 2024
% Define the triangular function
function y = tri(t)
y = max(0, 1 - abs(t));
end

Connectez-vous pour commenter.

Réponses (1)

Chunru
Chunru le 7 Mar 2024
The following line is problematic:
back_to_zero_indices = find(g1(t_values(nonzero_indices)) == 0, 1, 'last');
First, the function g1 return floating point value and the comparison with 0 is generally not working.
You may consider to use min (if you know there exist one point to be zero, or close to zero).
[~, back_to_zero_indices] = min(abs(g1(t_values(nonzero_indices))));
You can also consider something like:
back_to_zero_indices = find(abs(g1(t_values(nonzero_indices))) < 1e-5, 1, 'last');
% need to take care of empty indices case

Catégories

En savoir plus sur GPU Computing dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by