Using fprintf to print on several lines in Matlab - matlab

Question:
Write a procedure called Print7 to print all integer numbers within the range 0:100 that are divisible by 7. Ten numbers are to be printed on one output line. Hence write a program that invokes that procedure.
This is what I did
file = fopen('print7.dat','r');
x = 1:100
for x=[1:100]
if mod(x,7) == 0;
print7 = [x]
end
end
fprintf('print7 %d\n', print7)
Now it's output becomes the number 98 - which I understand to be the largest number under 100 divisible by 7. But I want a 10xn matrix-like result.
What do I do?

What you are doing stores your result in a variable and overwrites the variable in each iteration. You could print it directly instead like this:
c=0;
for x=[1:100]
if mod(x,7) == 0
fprintf('%3d',x)
c=c+1;
if mod(c,10) ==0
fprintf('\n')
end
end
end

fileID = fopen('print7.dat','r');
for x = 1:100
if(mod(x,7) == 0)
fprintf(fileID,'%d',x);
end %end of if
end %end of for
fclose(fileID);

Related

MATLAB - plot an iteration

The code so far:
function [fr]=frictionFactorFn(rho,mu,e,D,L,Q,f0,tol,imax)
format long
CS=(pi*D^(2))/4;%Cross sectional area of pipe
v=Q/CS;%velocity
Re=(rho*v*L)/mu;
iter=1;i=1;fr(1)=f0;
while 1
fr(i+1)=(-1.74*log((1.254/(Re*sqrt(fr(i))))+((e/D)/3.708)))^-2;%substitution for root finding
iter=iter+1;
if abs(fr(i+1)-fr(i))<tol || iter>=imax
break;
end
i=i+1;
end
fprintf('\n The Reynolds number is %f\n',Re);
plot(0:iter-1,fr);
xlabel('Number of iteration'),ylabel('friction factor');
end
It gave me the right converged value of f=0.005408015, but I would like to plot the iteration
Possibly by storing the values of f upon each iteration in an array. In this example the array is called Store_f and is plotted after the while-loop is completed. The variable Index below is used to indicate which cell of array Store_f the value should be saved to.
function [f_vals] = frictionfactorfn()
Index = 1;
while (Condition)
%Calculation code%
Store_f(Index) = f;
Index = Index + 1;
end
disp(num2str(f))
plot(Store_f,'Marker','.');
xlabel('Iteration'); ylabel('Value');
end

matlab code to prompt a user for input inside a loop

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);
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.

Matlab symbols used to terminate the loop

I am new to matlab and I have couple of questions about it. First one, "Your function should terminate the sequence when either the value of ... or..." I use || in the code but it does not work as expected while && gives me the correct answer. Second question, how could the code be to display only the final answer?
Problem: calculate X which is represented by the sequence below
X = 1 - 1/2^2 + 1/3^2 - 1/4^2 +....
Requirement: Your function should terminate the sequence when either the value of 1/k^2 is less than 0.0001 or k is equal to k_max.
input k
Initialize x = 0
for loop i from 1 to k
if 1/i^2<0.0001 && i >= 100
break
end
Calculate X = (-1)^(i+1)./i^2 + X
end
You can use the break function as follows, where END_CONDITION is the condition you want to end your loop in.
if END_CONDITION
disp(X);
break;
end
To display the final answer, you can use the disp function. Eg. if your variable you want to print is called A then you use the following code.
disp(A)
Collectively this is your code. Since k_max terminates at the end of the for loop, we don't have to add any conditions to break out of the loop.
X = 0;
for i = 1:k
if 1/i^2<0.0001 || i==100
break;
end
X = (-1)^(i+1)./i^2 + X;
end
disp(X);

matlab program to check whether the given input number is prime number or not

I need to find whether the given input number in MAT-LAB command window is prime number or not. I need to code without using the inbuilt command in matlab.
Am I programming your homework?
function result = isprime2(number)
result=true;
%% check if number is a nonnegative integer
if floor(number)~=number || number<0
result=false;
return
end
%% check if number can be divided by another integer
for k=2:(number/2)
if rem(number,k)==0
result=false;
return
end
end
The above answer is not correct....it consider 9 as prime number which is not
function result=myprime(n)
%result=true;
%check if number is a nonnegative integer
if floor(n)~=n || n<0
result=false;
return
end
% check if number can be divided by another integer
for k=2:(n/2)
if rem(n,k)==0
result=false;
return
end
end
result=true;
return
end
Calculation
a = input('Enter a value: ');
b = input ('Enter b value: ');
for(x = a : b)
if (isprime(x)==1)
fprintf('%d is prime number \n',x)
end
end
My program goes this way
function tf = isprim(n)
%this function will check whether the number is prime or not
tf = true;
for i = 2:n-1
if rem(n,i) == 0
tf = false;
break
end
end

Matlab function return value

I have one program that has function and the problem, return value, it has too many output.
Like exempley: y = text the answer comes up
Error in text (line 2)
if nargin == 0
Output argument "array" (and maybe others) not assigned during call to "
C:\Users\name\Documents\MATLAB\text.m>text".
The program text.m reads a txt file that contains a couple of names and numbers like
exemple:
John doughlas 15986
Filip duch 357852
and so on. The program convert them to 15986 Doughlas John and so on.
function array = text(~)
if nargin == 0
dirr = '.';
end
answer = dir(dirr);
k=1;
while k <= length(answer)
if answer(k).isdir
answer(k)=[];
else
filename{k}=answer(k).name;
k=k+1;
end
end
chose=menu( 'choose file',filename);
namn = char(filename(chose));
fid = fopen(namn, 'r');
R = textscan(fid,'%s %s %s');
x=-1;
k=0;
while x <= 24
x = k + 1;
All = [R{3}{x},' ',R{1}{x},' ',R{2}{x}];
disp(All)
k = k + 1;
end
fclose(fid);
Is there anyway to fix the problem without starting over from scratch?
Grateful for all the answers!
You specify the function output argument in the definition, but you don't assign anything to it in the function body.
For example, in
function y = student(j)
your output is y. So you have to assign something to y.
Read more about functions in MATLAB.
Here is a working example.
The first part is to create a function called 'functionA' in a filename 'functionA.m'. Then put the following code inside:
function result = functionA(N,alpha)
result = 5;
return
end
The second part is to create another Matlab file(i.e. upto you to name it) or you can use the Matlab command window even. Then run the following code:
getresult = functionA(100,10);
getresult
After running you get the following answer:
ans =
5