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

3 次查看(过去 30 天)
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);

回答(1 个)

Chunru
Chunru 2024-3-7
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

类别

Help CenterFile Exchange 中查找有关 GPU Computing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by