Borrar filtros
Borrar filtros

How can I get all inputs in same line, based on how many inputs the user defines at first?

6 visualizaciones (últimos 30 días)
Hi, so the user defines how many inputs is his equation 'n'. Then the for loop starts collecting all his inputs.
How can I collect all the x and y values in the same line? (cuurently it asks set amount of times based on 'n')code example.PNG
n=input('Enter the number of points : ');
x=[];
y=[];
for i=1:n
x(i)=input('Enter Temperature (x) = ');
y(i)=input('Enter h (y) = ');
end

Respuestas (1)

Yukthi S
Yukthi S el 19 de Abr. de 2024
Hi Omar
Based on your question, I got that you wanted to input all the x ,y values in the same prompt rather than using “n” no.of prompts. I am assuming you are using the latest version of MATLAB since you have not specified that. You can look into the below code for reference:
% enter all points at once, pairs separated by ";"
userInput = input('Enter all Temperature (x) and h (y) pairs separated by ";": ', 's');
% Split the input string into pairs
pairs = strsplit(userInput, ';');
% Determine the number of pairs (n)
n = length(pairs);
% Initialize arrays
x = zeros(1, n);
y = zeros(1, n);
% Parse each pair and assign to x and y arrays
for i = 1:n
% Convert each pair from string to numeric values
values = str2num(pairs{i});
if length(values) == 2 % Ensure each pair contains exactly two values
x(i) = values(1);
y(i) = values(2);
else
% Display error and exit if a pair does not contain exactly two values
error('Error: Each pair must contain exactly two numeric values.');
end
end
If you want to display the x and y values separately, you can add the below code snippet which displays all the entered x and y values.
% Display the collected x and y values
disp('All the entered x values (Temperature):');
disp(x);
disp('All the entered y values (h):');
disp(y);
Refer to the link attached below to know more about “strsplit”:

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by