How can I get all inputs in same line, based on how many inputs the user defines at first?
조회 수: 11 (최근 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')![code example.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/211750/code%20example.png)
![code example.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/211750/code%20example.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
댓글 수: 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!