functionmatlabplotsequence

# Graphing a sequence of functions in matlab

I want to graph the first 10 terms of the succession of functions.

For this I tried to do the following code in MATLAB:

``````n_max = 10;
x = linspace(0, 1, 1000);
fn_values = zeros(n_max, length(x));

for n = 1:n_max
fn = zeros(size(x));
for k = 0:(2^n - 1)
Ik = [(k / 2^n), ((k + 1) / 2^n)];
fn = fn + (k / 2^n) * (x >= Ik(1) & x < Ik(2));
end
fn_values(n, :) = fn;
end

figure;
hold on;
for n = 1:n_max
plot(x, fn_values(n, :), 'DisplayName', ['f_', num2str(n)]);
end

title('Graph of the first 10 terms of the sequence f_n(x)');
xlabel('x');
ylabel('f_n(x)');
legend('show');
grid on;
hold off;

``````

Can this work? Any help is appreciated!

Solution

• You can try the code below

``````n_max = 10;
x = linspace(0, 1, 1000);

f = @(n,x) sum(cell2mat(transpose(arrayfun(@(k) k*sum(x>=k./2.^n & x< (k+1)./2.^n, 1), 0:(2^n-1), UniformOutput=false))),1)/2^n;

figure;
hold on;
for n = 1:n_max
plot(x, f(n, x), 'DisplayName', ['f_{', num2str(n),'}']);
end

title('Graph of the first 10 terms of the sequence f_n(x)');
xlabel('x');
ylabel('f_n(x)');
legend('show');
grid on;
hold off;
``````