excel-like formula column

1 view (last 30 days)
Andy
Andy on 2 Jan 2024
matrix of two columns representing in the morning and in the day.
can we have a 3rd column that would compute the average of first 2 columns, and update dynamically when values in first 2 columns change ... how could this be achieved in Matlab?
thx

Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 2 Jan 2024
If understood correctly, this is what you are trying to achieve, e.g.:
% Initialize a matrix with two columns of data (Morning and Noon):
Morning = [8; 9; 7; 6; 5];
Noon = [15; 18; 20; 22; 13];
M = [Morning, Noon];
% Function Handle to compute the average dynamically:
Average_Computer = @(M) mean(M, 2);
% Display the initial matrix
disp('Initial Version of the Matrix: ');
Initial Version of the Matrix:
disp(M);
8 15 9 18 7 20 6 22 5 13
% Plot the initial matrix
figure;
h(1) = plot(M(:, 1), 'ro-', 'DisplayName', 'Morning');
hold on;
h(2) = plot(M(:, 2), 'bd-', 'DisplayName', 'Noon');
% Initialize the averaged value is the same as Morning data:
h(3) = plot(M(:, 1), 'kp-.','DisplayName', 'Averaged Data');
legend('show');
title('Morning and Noon Values with Average Values Computed Dynamically');
% Loop based Simulation of dynamic changes :)
for i = 1:5
% Simulate changing values in the first two columns using randi():
M(:, 1) = randi([5, 10], size(M, 1), 1);
M(:, 2) = randi([15, 25], size(M, 1), 1);
% Update the average column:
M(:, 3) = Average_Computer(M);
%Updating the above created plot:
set(h(1), 'YData', M(:, 1));
set(h(2), 'YData', M(:, 2));
set(h(3), 'YData', M(:, 3));
drawnow;
% Pause to see the changes:
pause(1);
end

Categories

Find more on Function Creation in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!