% --------------------------------------------------
% 1) Read the raw data
T = readtable('porucha.csv');  % T.Throttle, T.Pitch, T.RPM

% 2) Identify unique grid points
th_vals = unique(T.Throttle);    % [10 20 … 100]
p_vals  = unique(T.Pitch);       % e.g. [0 5 10 … 100]

% 3) Preallocate lookup matrix
RPM_lookup = nan(numel(th_vals), numel(p_vals));

% 4) Fill in by averaging
for i = 1:numel(th_vals)
    for j = 1:numel(p_vals)
        mask = T.Throttle==th_vals(i) & T.Pitch==p_vals(j);
        if any(mask)
            RPM_lookup(i,j) = mean(T.RPM(mask));
        end
    end
end

% 5) Display as a labeled table
rowNames = compose("Thr%g", th_vals);
varNames = compose("Pit%g", p_vals);
Tlookup = array2table(RPM_lookup, 'RowNames', rowNames, 'VariableNames', varNames);
disp(Tlookup)

% 6) Plot RPM vs. Pitch for each Throttle level
legendLabels = compose("%g%% výkon", th_vals);
figure;
hold on;
for i = 1:numel(th_vals)
    plot(p_vals, RPM_lookup(i,:), '-', 'LineWidth', 2, 'DisplayName', legendLabels{i});
end
xlabel('Náběh listů [%]', 'FontSize', 14);
ylabel('RPM',       'FontSize', 14);
legend('Location','southwest', 'FontSize', 14);
grid on;
hold off;

% 7) Save for Simulink
save('RPMlookup.mat','th_vals','p_vals','RPM_lookup');
