Matlab symbols used to terminate the loop - matlab

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

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

Terminate recursion after reaching certain condition

I've been experimenting with a Sudoku solver using recursion. The problem I've encountered it that the recursive function after finding the right solution will not terminate, but goes on until every number is tested at every position.
How do I terminate such loop in Matlab? Error condition 'error('...') within the function can break the execution, but is by no means a good solution to my problem.
Here is a sample code for similar recursion, producing all possible 2 element vectors for numbers from 1 to 4. I would like it to stop when both numbers are equal to 2.
%possible moves at each position
moveMat = zeros([1,2])+3;
lineInput = zeros([1,2]);
%start recursion
recurNumbers(moveMat, 0, lineInput)
function recurNumbers(moveMat, position, lineVariable)
position = position + 1;
%if all numbers are equal to 2 then try to exit the function
if ~all(lineVariable == 2)
%if all numbers are not equal to 2, try other combination
if position < length(lineVariable)+1
for move = 0 : moveMat(position)
moveMat(position) = move;
lineVariable(position) = lineVariable(position) + 1;
recurNumbers(moveMat,position,lineVariable)
disp(lineVariable)
end
end
else
disp(lineVariable)
return
end
end
Now it will print the vector '[2 2]' twice, which indicates that it recognised the condition, but the 'return' will not do what I imagined it to do.
Although it is not very clear to me what you are trying to achieve, I assume that the following function meets your stopping criterion.
function exit_fl = recurNumbers(moveMat, position, lineVariable)
exit_fl = 0;
if (all(lineVariable == 2))
% Show the result and exit
disp(lineVariable)
exit_fl = 1;
else
position = position + 1;
%if all numbers are not equal to 2, try other combination
if position < length(lineVariable)+1
for move = 0 : moveMat(position)
moveMat(position) = move;
lineVariable(position) = lineVariable(position) + 1;
% Receive the exit status of your function
ex_fl = recurNumbers(moveMat,position,lineVariable);
if (ex_fl == 1)
% If the criterion was met, then stop
exit_fl = 1;
return
end
end
end
end
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.

Check Position with for loop, not enough input arguments - Matlab

I made a simple function that loops between the rows and columns of an array using for loops. The loop is part of a function named checktakentest (Since I'm testing this method atm). I keep getting the error that there aren't enough input arguments.
function [spotTaken] = checktakentest(tttArray)
for h = 1:3
if tttArray(h,j) == 1
%Is spot is taken, break loop
spotTaken = 1; break;
else
spotTaken = 0;
end
for j=1:3
if tttArray(h,j) == 1
spotTaken = 1; break;
else
spotTaken = 0;
end
end
end
I tried also defining h and j previously as follows
h = [1,2,3];
j = [1,2,3];
Note that tttArray is a global variable defined in another function and its array values change in that function. A spot taken is 1, empty is 0. What arguments should I pass to the function and how do I know which ones to pass since this has been a recurring problem for me? A simple explanation would be appreciated. Note that I call the function via
checktakentest(tttArray)
Just remove the first if clause - at that point you don't have j initialized to a value, so you can't use it, yet:
function [spotTaken] = checktakentest(tttArray)
for h = 1:3
for j=1:3
if tttArray(h,j) == 1
spotTaken = 1; break;
else
spotTaken = 0;
end
end
end
If you call your function like this: checktakentest(tttArray) with tttArray beeing a mxn-matrix with m>2 and n>2 you should not get an error.
If you call it like this: checktakentest you will get the error you described (not enough input arguments).

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