Loops in Matlab - arrays

I get stuck when I initialize v(0)=0 and t(0)=0. Is the problem in not creating an empty array first? Your help is greatly appreciated.
T= 0.001;
C= 0.004;
n=0;
k=0;
v(0)=k;
t(0)=k;
while v(n)<60
v(n+1)= T.*(A(n)-C.*(v(n)).^2)+v(n);
t(n+1)= (n-1)*T;
n=n+1;
end
n60=n
t60=(n60-1)*T

Indices in Matlab are starting with 1.
Therefore v(0)=k and t(0)=k are not legal.
You rather do:
v(desired arraysize)=k;
t(desired arraysize)=k;
to pre-allocate.
and
v(1)=k;
t(1)=k;
to initialize the first value.
so v(n)<60 will give you an error as well.
you can write:
v(1) = 0;
while v(n) < 60+1
v(n+1)= T.*(A(n)-C.*(v(n)).^2)+v(n);
t(n+1)= (n-2)*T; %not completetely sure with this line, you should check it again.
n=n+1;
end
from comments:
just set t(1)=0 and v(1)=0, you simple need to rethink from other languages, that the indexing starts with 1. That basically means you cannot use the index as a substitute for "time" you usually need an additional time-vector, which relates your values with a certain time

Related

Calculate the mean of an array in MATLAB

I have an array in Matlab "Numbers" that is stored in the workspace as a 400x1 double. I know how to calculate the mean of this data, but the problem I have is actually writing the code to do this. I know there are functions built-in which I could use, but I want to try and calculate this using only low-level IO commands and I'm not sure how to go about doing this. I was thinking the correct way to do this would be to create a for loop and a variable containing the total that adds each element in the array until it reaches the end of the array. With that, I could simply divide the variable 'Total' by the number of elements '400' to get the mean. The main problem I have is not knowing how to get a for loop to search through each element of my array, any help in figuring that part out is much appreciated. Thank you.
mean(Numbers) will do it for you. If not,
sum(Numbers)/length(Numbers)
or, if you insist on not using built-in functions,
sums = 0;
counter = 0;
for val = Numbers
sums = sums + val;
counter = counter + 1;
end
Numbers_mean = sums/counter;
although this will almost always be slower than just calling mean.

End condition of an IF loop that depends on a 3D array

I'm writing a program which will move a particle about a cube, either left,right,up,down, back or forward depending on the value randomly generator by the program. The particle is able to move with cube of dimensions LxLxL. I wish the program to stop when the particle has been to all possible sites and the number of jumps taken output.
Currently I am doing this using an array[i][j][k] and when the particle has been to a position, changing the value of the array at that corresponding point to 0. However, in my IF loop I have to type out every possible combination of i,j and k in order to say if they are all equal to 0 the program should end. Would there be a better way to do this?
Thanks,
Beth
Yes. I'm assuming the if in question is the one contained within the triple nested loop who's body sets finish=1;. The better way of doing this is to set a your flag before the loop, beginning with a true value then setting it to false and breaking if you encounter a value other then zero. Your if statement becomes much simpler, like this;
int finish =1; // start with a true value
//loops are untouched so still got the for i and for j above this
for(k = 0; k < 15; k++)
{
if (list[i][j][k] != 0)
{
finish = 0;
break;
}
}
// outside all the loops
return finish;
I think this is what you're asking for but if not please edit your question to clarify. I'm not sure if there is some technical name for this concept but the idea is to choose your initial truth value based on what's most efficient. Given you have a 15x15x15 array and a single non-zero value means false, it's much better to begin with true and break as soon as you encounter a value that makes your statement false. Trying to go in the other direction is far more complicated and far less efficient.
Maybe you can add your list[i][j][k] to a collection every time list[i][j][k]=0. Then at the end of your program, check for the collection's length. If it's of the right length, then terminate..

Counting the times numbers occur in an array using (count_numbers(int [], int, int)) C

So what I have is an array that's size is decided by me and then the elements in the array are randomly generated. It's supposed to take an integer array,its size, and an integer number
and find how many times the number is present in the array and return that count at the end.I keep trying stuff and nothing seems to be getting me anywhere close to an answer. I was just trying to see if someone could point me in the right direction on where to start
count_numbers(int array[], int size, int z)
Hhave you tried running a loop through the array and trying a match expression to the array value in another loop. This seems like a logic question rather than actual code related. Maybe a search around the internet looking at how to count in arrays could help you.
This should point you in the right direction...
for (int i = 0; i < arraySize; i++) {
if (array[i] == z /*z being your search value**/) {
you may have to alter this a little
//dosomething
// e.g. increment a count here
}
else
do-nothing essentially.
There is a method for checking array size - so don't worry about defining it's size. have a look at the java method for this and use it.
Hope this helps

Appending to array within a loop

I am a SAS programmer learning R.
I have a matrix receivables read from a csv file.
I wish to read the value in the "transit" column, if the value of "id" column of a row is >= 1100000000.
I did this (loop 1):
x = vector()
for (i in 1:length(receivables[,"transit"])){
if(receivables[i,"id"] >= 1100000000){
append(x, receivables[i,"transit"]);
}
}
But, it does not work because after running the loop x is still empty.
>x
logical(0)
However, I was able to accomplish my task with (loop 2):
k=0
x=vector()
for (i in 1:length(receivables[,"transit"])){
if(receivables[i,"id"] >= 1100000000){
k=k+1
x[k] = receivables[i,"transit"]
}
}
Or, with (loop 3):
x = vector()
for (i in 1:length(receivables[,"transit"])){
if(receivables[i,"id"] >= 1100000000){
x <- append(x, receivables[i,"transit"]);
}
}
Why didn't the append function work in the loop as it would in command line?
Actually, to teach me how to fish, what is the attitude/beatitude one must bear in mind when operating functions in a loop as opposed to operating them in command line.
Which is more efficient? Loop 2 or loop 3?
Ok, a few things.
append didn't work in your first attempt because you did not assign the result to anything. In general, R does not work "in place". It is more of a functional language, which means that changes must always be assigned to something. (There are exceptions, but trying to bend this rule too early will get you in trouble.)
A bigger point is that "growing" objects in R is a big no-no. You will quickly start to wonder why anyone could possible use R, because growing objects like this will quickly become very, very slow.
Instead, learn to use vectorized operations, like:
receivables[receivables[,"id"] >= 1100000000,"transit"]

C two dimensional array smallest gets biggest instead

I am new to stackoverflow as am new to programming, yet am not really a 'professional and enthusiast programmer'. Enthusiast maybe but not professional...
In a part of some beginner code of mine i have a two dimensional array diff[i][j], where the value is zero wherever i==j. I am trying to get the smallest value in each row but not the zero value...
the part of the code (under construction) that searches the smallest of the first row is:
i=1;
double smallest;
for ( j=1 ; j<=n ; j++ )
{
smallest = diff[i][j];
if ( j!=i && diff[i][j] < smallest )
smallest = diff[i][j];
}
printf("\n %lf\n", smallest);
however, the result is always the biggest number not the smallest. Anyone knows why??
P.S. I'd be thankful for any suggestion or comment of dealing with stackoverflow.com and the way i asked my question, since am new here... thank you in advance...
EDIT
after the answers below, i decided to make the i=1 a special case and make two separate functions for both cases... however, when i try to assign j to other variable i failed... in the previous code:
if (j!=i && diff[i][j]<smallest) {smallest=diff[i][j]; d=j}
declared d previously and everything... when i print d it prints a random number >maybe the memory location content... tried for debugging to assign an initial value - with the declaration - and when printing it came out the initial value... the point is i want d to hold the column where the smallest value is... how can i acheive that??
You never initialize smallest
i=1;
double smallest = diff[1][2]; // initialize it to a non-diagonal element in the column
for (j=1; j<=n; j++)
if (j!=i && diff[i][j]<smallest){
smallest=diff[i][j];
}
printf("\n %lf\n", smallest);
EDIT:
You also seem to have { smallest= diff[i][j]; .. } in your code that overrides the value of smallest each iteration. I removed it in my answer.
First thing, array indexes start from 0 in C, not 1, so you should have j = 0; j < n, assuming n is the size of the array.
Then, you assign to smallest every time around the loop, not just if the new value is smaller. So, what you're seeing is the last value.
Assuming that you really do run one past the end of the row, this "last value" is probably actually the first value in the next row. Or some arbitrary value stored in the memory that just so happens to be past the end of the array, if your array has exactly 2 rows. Anyway, it's Undefined Behavior to read past the end of an array, which is Not Good. Anything is allowed to happen, and what does happen often is more puzzling than you expect.
Careful about your array indexes. In C array indexes start at zero.
For:
double array[10];
you would go through all ten elements with:
int i;
for( i = 0; i < 10; i++ )
printf( "The array value at %d is %g\n", i, array[i] );

Resources