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

2 ビュー (過去 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);
  2 件のコメント
Walter Roberson
Walter Roberson 2024 年 3 月 7 日
We need tri in order to be able to test
Inmer Jimenez
Inmer Jimenez 2024 年 3 月 7 日
編集済み: Inmer Jimenez 2024 年 3 月 7 日
% Define the triangular function
function y = tri(t)
y = max(0, 1 - abs(t));
end

サインインしてコメントする。

回答 (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 Center および File ExchangeGPU Computing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by