How can I get all inputs in same line, based on how many inputs the user defines at first?
18 次查看(过去 30 天)
显示 更早的评论
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')
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
0 个评论
回答(1 个)
Yukthi S
2024-4-19
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”:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!