Search code examples
matlabsymbolic-math

How to request multiple inputs, n number of times


For the code below, I want to take the input values b and k, n times:

syms Q i w h2 h1 k

% n is number of layers for computation

n = input (' ')

for j = 1:n

k1 = input (' '); b1 = input (' ');

% up to... 

k(n) = input (' '); b(n) = input (' ');

% so that i want to use the various inputs of b and k to calculate Q.

Qi=( -b(i) * k(i) )*((h2-h1)/w)

Q=symsum(Qi, i, 1, 3)

Solution

  • Within your loop, you can prompt for the input and store it into an array of k and b values

    % Pre-allocate k and b arrays
    k = zeros(1, n);
    b = zeros(1, n);
    
    for ind = 1:n
        % Prompt for the next k value
        k(ind) = input('');
    
        % Prompt for the next b value
        b(ind) = input('');
    end
    

    Alternately, you could prompt the user for an array directly

    k = input('Please enter an array for k in the form [k1, k2, k3]');
    b = input('Please enter an array for b in the form [b1, b2, b3]');
    

    Using these arrays you could compute Q for each value of k and b

    Q = (-b .* k)*((h2-h1)/w);