1

I was asked to write a matlab code to calculate the mean of 5 numbers utilizing a loop structure, I wrote this code but I was wondering if I could do something to make matlab ask me to enter the values in order 1 to 5, for example " Enter Value 1 " " Enter Value 2" , etc.

sumx = 0;
N = 5;
i=1;
for n =1:N
i=i+1;
Valuei=input('Enter Values= '); 
sumx = sumx+Valuei;
end
Ybar=sumx/5;
display(Ybar);

1 Answer 1

2

You need sprintf:

N = 5;
for n = 1:N
   prompt = sprintf('Enter Value %d=', n);
   Value = input(prompt);
   ...
end

The %d is replaced by the value of n for each iteration of the loop.

Also, the variable i isn't used. You can get rid of it. It's a bad idea to use i (or j) as a variable name anyway since it's already defined by Matlab to be the imaginary unit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.