Iterate numbers within an fprintf - matlab

I have the following code in MATLAB. I want to iterate numbers 1, 2, and 3 sequentially in the filename(%d) section of the code such that if I turn on all tracks, each if statement will print filename(1), filename(2), filename(3). If I turn off B_track, A_track will print filename(1) and C_track will print filename(2). How can I iterate numbers within an fprintf so that filename(%d) prints out sequentially based on the tracks I turn on and off?
A_track = 1;
B_track = 0;
C_track = 1;
fid=fopen('test.txt','w');
if A_track ==1, i=1;
fprintf(fid,'\n\n');
fprintf(fid,[' filename(%d)=''test1'' \n'],i);
fprintf(fid,' idtrack(%d)=A_track \n',i);
end
if B_track ==1, i=2;
fprintf(fid,'\n\n');
fprintf(fid,[' filename(%d)=''test2'' \n'],i);
fprintf(fid,' idtrack(%d)=B_track \n',i);
end
if C_track ==1, i=3;
fprintf(fid,'\n\n');
fprintf(fid,[' filename(%d)=''test3'' \n'],i);
fprintf(fid,' idtrack(%d)=C_track \n',i);
end
fclose(fid);

I think this is what you intend to accomplish: i is set to 1 at the start, and for every item printed out, it is incremented by one. This way, no matter which tracks are on or off, the ones that are on will print with a sequential i.
A_track = 1;
B_track = 0;
C_track = 1;
fid = fopen('test.txt','w');
i = 1;
if A_track
fprintf(fid,'\n\n');
fprintf(fid,[' filename(%d)=''test1'' \n'],i);
fprintf(fid,' idtrack(%d)=A_track \n',i);
i = i+1;
end
if B_track
fprintf(fid,'\n\n');
fprintf(fid,[' filename(%d)=''test2'' \n'],i);
fprintf(fid,' idtrack(%d)=B_track \n',i);
i = i+1;
end
if C_track
fprintf(fid,'\n\n');
fprintf(fid,[' filename(%d)=''test3'' \n'],i);
fprintf(fid,' idtrack(%d)=C_track \n',i);
i = i+1;
end
fclose(fid);
I also changed your if A_track==1 to if A_track. I find this easier to read. You can use true and false values to define each of the track variables, if that makes more sense to you. But true and 1 are identical for all purposes.

For iteration of numbers the easiest trick is to use the mod() function.
You set the divider and that sets the size of the list you want to iterate over.
As mod() will return 0 you have to add 1 to it, as matlab indexes matrices starting at 1 and not 0. (most programming languages start at 0)
So let's say you have a for loop and you want to iterate over the numbers 1, 2 and 3. Then it would look something like this
for ii=0:10
nmbtoprint=mod(ii,3)+1;
fprintf(fid,[' filename=''test_%1'' \n'],nmbtoprint);
end
You don't need to use a for loop for every if statement as long as you have a general counter. For a general counter you can create any variable and just make sure that it updates (adds 1 wherever you need it to in the script).
i=1; %number at which you initiate your variable
if %check if true then do something
%run some piece of code
i=i+1; %increase the counter by 1
end
Also you can use a (cell) array.
idtoprint1=[0,1,10,100];
idtoprint2={'first','B','3rd'};
for ii=0:10
ida1=mod(ii,4)+1;
ida2=mod(ii,3)+1;
fprintf(fid,[' filename=''test_%i'' \n'],idtoprint1(ida1));
fprintf(fid,[' filename=''test_%s'' \n'],idtoprint2{ida2});
end

Related

MATLAB store value of looping to table form

I have the following working code which display parameter count after each hour. The code use two function. Basically my code does
User run test_main(hour, total parameter)
test_main generate random number
test_main send number to test_sub
test_sub respond to the number
test_main function
function[] = test_main(x, pc)
for i = 1:x %loop for time
fprintf('\n Time is %d hour after count start . \n', i);
for t = 1:pc
fprintf('\nPARAMETER at test main %d ', t);
w=rand; %random error generator.
if w<0.5
status=1;
else
status=99;
end
% fprintf('\n Time is %d hour after count start . \n', i);
test_sub(status);
end
end
end
test_sub function
function[a] = test_sub(z)
%fprintf('\nPARAMETER inside test sub %d ', count)
fprintf('\n Value is %d \n', z);
if (z==1) %if input equal to 0
j=1; %store temporary value to j
a=j;
disp('new value is 1')
elseif (z==99)
j=1;
a=j;
disp('new value is 100')
else
disp('unidentified error')
end
end
I notice that i haven't send a value back from test_sub to test_main. Im not sure how to record the value after each loop into table form. I need the table looks like:
Parameter 1 Parameter 2 ..... parameter N
Time 1 1 100
Time 2 100 1
....
Time N
Can the parameter and time expand according to the value that user insert at the test_main function?
ok i am not quite sure what the function does, but creating the table you want might be enough. i am assuming x and pc are just numbers and you have no name for each parameter . I would create a cell array first then transform it into a table:
function [output] = test_main(x, pc) %this functions output would be the table you want
cell_array=cell(x,pc+1); %creating a cellarray first
names=cell(1,pc+1);
names{1,1}='Time';
for i = 1:x %loop for time
fprintf('\n Time is %d hour after count start . \n', i);
cell_array{i,1}=i;
for t = 1:pc
fprintf('\nPARAMETER at test main %d ', t);
w=rand; %random error generator.
if w<0.5
status=1;
else
status=99;
end
% fprintf('\n Time is %d hour after count start . \n', i);
cell_array{i,t+1}=test_sub(status); %writing in row i at column t the value of test_sub
names{1,t+1}=['Parameter_' num2str(t)];
end
end
output=cell2table(cell_array,'VariableNames',names); %transforming it into a table
end
in the test_sub you write on both cases of the if 'a=1' i feel like the second should be a 100. The output looks like your example but the parameternames arent changed to 'Parameter X'. you can do that in the cell2table if you want

How to compute the number of operations of jacobi iteration in matlab

I want to compute the number of operations of jacobi iteration in matlab
I do not know how to do it !!!
Can you help me ?
Thanks
Here is my code for newton method :
b=zeros(30,1);
b(6)=2;
alpha=1;
A=zeros(30,30);
A(1,1)=-(2+alpha);
A(1,2)=1;
for ii=2:29
A(ii,ii-1)=1
A(ii,ii)=-(2+alpha)
A(ii,ii+1)=1
end
A(30,29)=1;
A(30,30)=-(2+alpha);
D=diag(diag(A));
R=A-D;
x=zeros(30,1);
for ii=1:100
xk= inv(D)*(b-R*x);
if(norm(xk-x,1)<=10^-5)
break;
end
x=xk;
end
ii
You have counted it, actually.
In case of code
for ii=1:N
%% Code
end
the ii variable works like the counter.
Reading the code step-by-step you:
Define anonymous temporary array, say forII with elements 1 to N with default step of 1.
For each iteration the appropriate element of original forII is assigned to ii
%% Code is executed
New value of ii scalar is assigned.
This behaviour allows:
Use counter=1:N as true counter.
Loop easily over elements of any array, for example for foo='Hello World!'.
Use predefined indices, array elements, etc. for ii=A.
When the for loop is terminated by break or return prompt the elements in queue are not assigned and ii keeps the last assigned value.
You can try
kk=0;
for ii=1:N
kk=kk+1;
if ii==5
break
end
end
disp(['kk = ' num2str(kk) '; ii = ' num2str(ii)]);
kk=0;
for ii='Hello World!'
kk=kk+1;
if ii=='r'
break
end
end
disp(['kk = ' num2str(kk) '; ii = ' num2str(ii)]);

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.

Storing the number of iterations of a nested loop in an array

I am relatively new to MATLAB and I am quite stuck in a specific problem.
I have an equation that I am trying to solve using a while loop. It works by guessing a certain parameter e_0 and filling it into the equation, until it converges. An example is found below, where the initial guessing value equals 100:
clear all
i=1;
e_0=100
e_1= e_0 + log(0.6) - log(exp(e_0)/(exp(e_0)+1))
while( i < 1e10 & abs((e_1 - e_0)) > 1e-12),
i = i + 1;
e_0=e_1;
e_1= e_0+log(0.6)-log(exp(e_0)/(exp(e_0)+1))
end
i
Now I would like the exact same procedure but then for multiple values of e_0 at the same time, e.g. 101, 102, 103 and so on, and count how many more iterations those will take. I reckon that I therefore need to put a for-loop for that. I thought something like this:
clear all
i=1;
for e_0 = 100:105
e_1= e_0+log(0.6)-log(exp(e_0)/(exp(e_0)+1))
while( i < 1e10 & abs((e_1 - e_0)) > 1e-12),
i = i + 1;
e_0=e_1;
e_1= e_0+log(0.6)-log(exp(e_0)/(exp(e_0)+1))
end
end
i
However, now all the iterations from the different guessing values are shown underneath each other, and I get a total of 1519 iterations. How can I for example store the number of iterations needed for every initial guessing value underneath each other into a variable?
I hope it is clear enough... Thank you!
How about this:
i = 0;
offset = 99;
for n = 1:6
e_0 = n + offset;
e_1 = e_0+log(0.6)-log(exp(e_0)/(exp(e_0)+1))
while( i < 1e10 & abs((e_1 - e_0)) > 1e-12),
i = i + 1;
This part needs to change to prevent e_0 to be redefined inside the loop:
e_1= e_1+log(0.6)-log(exp(e_1)/(exp(e_1)+1))
end
iterations(n)=i;
end
Note: it is not recommended to use i as a loop increment, since it redefines i used in complex numbers.

Using fprintf to print on several lines in 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);