How to save results from my script in vectors in Matlab? - matlab

I was wondering if someone could help me with MatLab.
Is there a way to save these 2 values count_zero and count_value into 2 vectors.
The part of interest in the following code is inside the while loop, the upper part is irrelevant for this question.
For example all values of count_zero should be saved in vector a=[count_zero count_zero ..] and all values of count_value in vector b=[count_value count_value ...].
This is my code, thanks in advance.
threeminutesofvideo_Youtube;
h=[0:0.5:179];
for idx=1:length(h)
threshold=h(idx);
m =find(threshold-1<=x & x<=threshold);
Y(idx)=sum(y(m));
end
count_zero=0;
count_value=0;
i=1;
while i<length(Y)
if (Y(i)==0)
count_zero=count_zero+1;
i=i+1;
while Y(i)==0 && i<length(Y)
count_zero=count_zero+1;
i=i+1;
end
if i<(length(Y))
count_zero
count_zero=0;
end
if i==(length(Y)) && Y(length(Y))~=0
count_value=1;
count_value
count_value=0;
elseif i==(length(Y)) && Y(length(Y))==0
count_zero=count_zero + 1;
count_zero
count_zero=0;
end
else
count_value=count_value+1;
i=i+1;
while Y(i)~=0 && i<length(Y)
count_value=count_value+1;
i=i+1;
end
if i<(length(Y))
count_value
count_value=0;
end
if i==(length(Y)) && Y(length(Y))~=0
count_value=count_value+1;
count_value
count_value=0;
elseif i==(length(Y)) && Y(length(Y))==0
count_zero=1;
count_zero
count_zero=0;
end
end
end

As far as I have understood you want to memorize the values in a vector, not to save to file don't you?
In this case let us call the vector in which you want to memorize If you know a priori the number of values you want to memorize you can do this
a = NaN*ones(num_of_values,1);
i=1;
while condition
...
a(i) = temp_val;
i = i+1;
end
If you don't know the number of values a priori:
a=[];
i=1;
while condition
...
a = [a;temp_val];
i=i+1;
end
I hope to have been helpful

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 executes the first statement even if is false

I have the following function in matlab. I am trying to shuffle a matrix. But somehow matlab keeps executing the code from if even if the statement should go to else. And when it comes to else I have to put some aditional code, even if all it does is **i+1. It is normal for matlab or am I missing something?
function magic_matrix = magicsquare1(matrix,n)
magic_matrix=ones(n,n)*(-1);
i=3-1;
j=4+1;
for ki=1:n
for kj=1:n
if(i<1)
i=n;
end
if(j>n)
j=1;
end
if magic_matrix(i,j) == -1
magic_matrix(i,j)=matrix(ki,kj);
%X = sprintf('i=%d j=%d',i,j);
%disp(X)
i=i-1;
j=j+1;
else
i=i+2;
j=j-1;
if(i>n)
i=1;
end
if(j<1)
j=n;
end
magic_matrix(i,j)=matrix(ki,kj);
% X = sprintf('i=%d / j=%d',i,j);
%disp(X)
i=i-1;
j=j+1;
end
end
end

Smarter way to index loops in Matlab

I have written a function (call it F) that works "well" (i.e. gives me the result I want) and inside it I call the exact same function (call it G_i) four times (below one of them) except each time I change the way I index my loop to be able to cover all pairs of coefficients in a matrix. I think this method is poor and I would like to know if you have ideas to improve it please...
I do this to check sequentially conditions on the coefficients of a matrix (sometimes in the order (1,2) then (1,3) then (2,3). I go on checking in different orders).
function G_1=countbackward(a,,,)
n=a;
G_1=[];
N=1;
while N>0
for l=n:-1:1
for m=1:l
if some condition on generated matrices
...
elseif another condition on generated matrices
...
else
N=0 ;
end
G_1=[G_1,g_0] ;
end
end
end
(for n=3 I get with the above the entries: (3,1),(3,2),(2,1).)
Other indexing I use with the exact same body of the above function :
for l=n:-1:1
for m=(l-1):-1:1
Same for the following:
for l=1:n
for m=l+1:n
Same for the following:
for l=1:n
for m=n:-1:l
Thank you for your help.
APPENDIX:
below is a simplified example of my code:
function H=count2backward(a,g_0,s,e)
%matrix g_0 is the "start" matrix
%matrix g_K is the "end" matrix
n=a; % number of nodes in an undirected graph or size A
s=mypayoff(n,g_0);
e=mypayoff(n,g_K);
H=[];
N=1;
while N>0
for l=1:n
for m=n:-1:l
if l~=m && g_0(l,m)==0 && s(l)<=e(l) && s(m)<=e(m) && (s(l)<e(l) || s(m)<e(m) ) ;
g_0(l,m)=g_0(l,m)+1 ;
g_0(m,l)=g_0(m,l)+1 ;
g_0 ;
s=mypayoff(n,g_0);
elseif l~=m && g_0(l,m)==1 && (s(l)<e(l) || s(m)<e(m) ) ;
g_0(l,m)=g_0(l,m)-1 ;
g_0(m,l)=g_0(m,l)-1 ;
g_0 ;
s=mypayoff(n,g_0);
else
N=0;
end
H=[H,g_0] ;
end
end
end
You can generate the indexes and pass them as a parameter. That lets you abstract deciding how to loop into another function.
indexes = countbackwardpattern(a);
G_1=g_i(a, indexes);

Code returns minimal m s.t P(X>m)=1/n^2 for binomial experiment

Assume we do an experiment where we throw n balls into n jars. X is an independent variable describes number of balls int the first jar. Build a function returns the smallest integer fulfills P(X>m)<1/n^2.
The distribution is binomial so I wrote the following matlab function:
function m = intpq3(n)
flag=0;
par=1/n^2;
m=0;
P=0;
%Since X is non-neative integer
if(n==1)
m=-1*Inf;
else
while(flag==0 && m<=n)
m=m+1;
P=P+nchoosek(n,m)*(1/n)^m*(1-1/n)^(n-m);
if(1-P<=par)
flag=1;
end
end
end
disp(m)
end
But for every 'n' I give it, it returns either error or n-1. What am I doing wrong?
The following version of your program seems to do what you want. The problem with your version as far as I can tell is that you did not include m=0 into your sum of P, thus 1-P was consistently too large. It's always a good idea to ask the program to spit out numbers and compare to paper-and-pencil calculations.
function [m,P] = intpq3(n,varargin);
if nargin==2
plt=varargin{1};
else
plt = 0;
end
flag=0;
par=1/n^2;
m=0;
P=0;
disp(['1/n^2 = ' num2str(par)]);
%Since X is non-neative integer
if(n==1)
m=-1*Inf;
else
while m<n & flag==0
P=P+nchoosek(n,m)*(1/n)^m*(1-1/n)^(n-m);
disp([' n= ' num2str(n) ' m= ' num2str(m) ' P(X>' num2str(m) ') ' num2str(1-P)])
if(1-P<=par)
flag=1;
end
m=m+1;
end
end
disp(['mselect = ' num2str(m-1)]);
end
The following also helped to diagnose the problem. It shows values of P(X>m) (colored dots) for different m at select values of n. Overlayed as a dashed line is 1/n^2.

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