My program is meant to calculate the linear regression coefficients given the array "input" using least squares method. My issue is when attempting to calculate the slope of data. As you can see the array "input" is a 2 row array. I was able to separate the two rows as input[i] and input[j]. But in order to find the slope I need to use these two rows separately and increment them in the equation to solve for v. How do I use these two arrays to get the value of v?
Note: Using the input shown in the image below, v and be should be 2.795 and -3.891 respectively.
My assignment:
http://i1306.photobucket.com/albums/s576/sammyr2011/assignment2question4_zps08a5464b.jpg
My code so far:
/*
* Program: linreg.c
* A program that calculates the linear regression coefficients
* v and b using the least squares method.
*/
#include <stdio.h>
#include "forStatLib.h"
double input[][10] ={{0, 5, 10, 15, 20, 25, 30 ,35, 40, 45}, {0, 13, 22, 37, 54, 62, 64, 100, 112, 126}};
// Use the sum += when inputting array into equation
int main() {
int first, second, i, j, k;
double v, b, t, y;
//grab 1st row of the array
for(i=0; input[0][i] ; i++) {
input[i];
}
//grab 2nd row of the array
for(i=0; input[1][i]; i++) {
input[j];
}
/*calculate the average of both rows, first row is t and second is y.
Then assign the averages of each as t_a and y_a. */
double t_a, y_a;
t_a = mean(10, input[i]);
y_a = mean(10, input[j]);
//calculate v (slope), Maybe use two loops with one nested?
// i need to increment
v = ( - t_a)( - y_a) / ( )
}
make these changes,
t_a = mean(10, input[0]);
y_a = mean(10, input[1]);
//calculate v (slope), Maybe use two loops with one nested?
// i need to increment
v1=0;
v2=0;
for(i=0; i< 10; i++)
{
v1+ = ( input[0][i] - t_a)*( input[1][i] - y_a);
}
for(i=0; i< 10; i++)
{
v2=v2+( input[0][i] - t_a)*( input[0][i] - t_a);
}
v=v1/v2; //use float or double data type
input[][] is a 2D array so to access the elements use input[i][j] form.
and i dont know why you used,
for(i=0; input[0][i] ; i++) {
input[i];
}
//grab 2nd row of the array
for(i=0; input[1][i]; i++) {
input[j]; // j not initialized
}
if to print the values use printf()
for(i=0; i<10 ; i++) {
printf("%d",input[0][i]);
}
//grab 2nd row of the array
for(i=0; i<10; i++) {
printf("%d",input[1][i]);
}
I wont give you the answer to your question or to your assignment, but something I think you will need a lot more at the moment: it seems you haven't really got a grasp on array manipulation. I'll try explain what your code is doing, so then you can modify / write / debug this and other code.
//grab 1st row of the array
for(i=0; input[0][i] ; i++) {
input[i];
}
What you have done till here is to increment the values of of i step by step till input[0][i]=0. For loops are written as follows for(do_this_once_in_the_begining;Keep_looping_if_this_is_true;do_this_once_per_loop) In C false=0 and true=nonzero.
str="my string"; for(i=0; str[i] ; i++) will work because the last element of any string is the number 0 (not the ascii character'0'). This wont work for an array f integers.
In the body of the loop you just read each element of the array and did nothing to it. If you wanted to you might have put a printf("%f",input[0][j]) so you view the elements. However, this does not do anything else.
And you don't need to "grab" anything. Your array was all setup when you declared it.. nothing more needed to be done.
The last part:
Your formula has two separate sigmas that are calculated separately, so you will need to use two for loops (you can do it in one, try figure it out, it will go a long way in solving other problems) BUT, you are not required to take a sigma of a sigma, so you wont need to nest them.
For example just calculate the v_denominator like this:
double v_denom=0;
for(i=0;i<10;i++){
v_denom+=( input[0][i] - t_a)*( input[0][i] - t_a);
}
try this
for(i=0 ; i < 10 ; i++)
v +=(input[0][i]-t_a)*(input[1][i]-t_y);//numerator
similarly calculate denominator and divide
Related
Task: Calculate the 25 values of the function y = ax'2 + bx + c on the interval [e, f], save them in the array Y and find the minimum and maximum values in this array.
#include <stdio.h>
#include <math.h>
int main()
{
float Y[25];
int i;
int x=3,a,b,c;
double y = a*pow(x,2)+b*x+c;
printf("a = ", b);
scanf("%d", &a);
printf("b = ", a);
scanf("%d", &b);
printf("c = ", c);
scanf("%d", &c);
for(i=0;i<25;i++)
{
printf("%f",y); //output results, not needed
x++;
}
system("pause");
}
Problems:
Cant understand how can I use "interval [e,f]" here
Cant understand how to save values to array using C libraries
Cant understand how to write/make a cycle, which will find the
minimum and maximum values
Finally, dont know what exactly i need to do to solve task
You must first ask the user for the values of a, b, c or initialize those variables, and ask for the interval values of e, f, or initialize those variables.
Now you must calculate double interval= (f - e)/25.0 so you have the interval.
Then you must have a loop for (int i=0, double x=e; i<25; i++, x += interval) and calculate each value of the function. You can choose to store the result in an array (declare one at the top) or print them directly.
Problems:
Cant understand how can I use "interval [e,f]" here
(f-e) / 25(interval steps)
Cant understand how to save values to array using C libraries
You need to use some form of loop to traverse the array and save the result of your calculation at every interval step. Something like this:
for(int i = 0; i < SIZE; i++)
// SIZE in this case 25, so you traverse from 0-24 since arrays start 0
Cant understand how to write/make a cycle, which will find the minimum and maximum values
For both cases:
traverse the array with some form of loop and check every item e.g. (again) something like this: for(int i = 0; i < SIZE; i++)
For min:
Initialize a double value(key) with the first element of your array
Loop through your array searching for elements smaller than your initial key value.
if your array at position i is smaller than key, save key = array[i];
For max:
Initialize a double value(key) with 0;
Loop through your array searching for elements bigger than your initial key value.
if your array at position i is bigger than key, save key = array[i];
Finally, dont know what exactly i need to do to solve task
Initialize your variables(yourself or through user input)
Create a function that calculates a*x^2 + b*x + c n times for every step of your interval.
Create a function for min & max that loops through your array and returns the smallest/biggest value.
Thats pretty much it. I will refrain from posting code(for now), since this looks like an assignment to me and I am confident that you can write the code with the information #Paul Ogilvie & I have provided yourself. Good Luck
#include<stdio.h>
#include<math.h>
int main()
{
double y[25];
double x,a,b,c,e,f;
int i,j=0;
printf("Enter a:",&a);
scanf("%lf",&a);
printf("Enter b:",&b);
scanf("%lf",&b);
printf("Enter c:",&c);
scanf("%lf",&c);
printf("Starting Range:",&e);
scanf("%lf",&e);
printf("Ending Range:",&f);
scanf("%lf",&f);
for(i=e;i<=f;i++)
{
y[j++]=(a*pow(i,2))+(b*i)+c;
}
printf("\nThe Maximum element in the given interval is %lf",y[j-1]);
printf("\nThe Minimum element in the given interval is %lf",y[0]);
}
Good LUCK!
int squaring_function (int *array, int i);
int main()
{
int array[5];
int i;
for(i=0; (i <= 5) ; i++)
{
array[i] = i;
printf("\nArray value %d is %d",i,array[i]);
}
for(i=0; (i <= 5) ; i++)
{
array[i] = (squaring_function(array, i));
printf("\nSquared array value %d is %d",i,array[i]);
}
return 0;
}
int squaring_function (int *array, int i)
{
return pow((array[i]),2);
}
I'm trying to use this squaring_function to square each value in turn in my array (containing integers 0 to 5). It seems to work however the last value (which should be 5)^2 is not coming up as 25. cmd window
I have tried reducing the array size to 5 (so the last value is 4) however this prints an incorrect number also.
I'm quite new to C and don't understand why this last value is failing.
I'm aware I could do this without a separate function however I'd quite like to learn why this isn't working.
Any help would be much appreciated.
Thanks,
Dan.
There are 2 bugs in your code. First is that you're accessing array out of bounds. The memory rule is that with n elements the indices must be smaller than n, hence < 5, not <= 5. And if you want to count up to 5, then you must declare
int array[6];
The other problem is that your code calculates pow(5, 2) as 24.99999999 which gets truncated to 24. The number 24 went to the memory location immediately after array overwriting i; which then lead to array[i] evaluating to array[24] which happened to be all zeroes.
Use array[i] * array[i] instead of pow to ensure that the calculation is done with integers.
The code
int array[5];
for(int i=0; (i <= 5) ; i++)
exceeds array bounds and introduces undefined behaviour. Note that 0..5 are actually 6 values, not 5. If you though see some "meaningful" output, well - good or bad luck - it's just the result of undefined behaviour, which can be everything (including sometimes meaningful values).
Your array isn't big enough to hold all the values.
An array of size 5 has indexes from 0 - 4. So array[5] is off the end of the array. Reading or writing past the end of an array invokes undefined behavior.
Increase the size of the array to 6 to fit the values you want.
int array[6];
The other answers show the flaws in the posted code.
If your goal is to square each element of an array, you can either write a function which square a value
void square(int *x)
{
*x *= *x;
}
and apply it to every element of an array or write a function which takes an entire array as an input and perform that transformation:
void square_array(int size, int arr[size])
{
for (int i = 0; i < size; ++i)
{
arr[i] *= arr[i];
}
}
// ... where given an array like
int nums[5] = {1, 2, 3, 4, 5};
// you can call it like this
square_array(5, nums); // -> {1, 4, 9, 16, 25}
First of all, I would like to know if its possible. If so, please checkout my code and tell me what is wrong.
int m[n]; // this is where I pass the values to a array
for(int i=0;i<n;i++) {
scanf("%d",&a);
m[i]=a;
}
int v[n][b]; // this is where I pass the values from a array to a 2d array
for(int i=0;i<n;i++) { // but for some reason it doesnt work
for(int j=0;j<b;j++) {
v[i][j]=m[i];
}
}
}
The output is :
something like this
v[0][0]:0
v[0][1]:0
v[1][0]:1
v[1][1]:1
....
but I want something like this:
v[0][0]:0
v[0][1]:1
v[1][0]:2
v[1][1]:3
without repeating the values
P.S- if I need to use pointers you can also explain me that way but I would prefer the first one.
In assigning to v[i][j], you are constantly reassigning whatever value was in m[i].
Instead try:
v[i][j] = m[i*n + j];
This is only going to work if the array m has n*b elements.
i*n represents the row you're working on, and j is the column. Or vice-versa, it's up to you how you imagine it.
#include <stdio.h>
int main(){
int m[6]; // this is where I pass the values to a array
int i;
int j;
int k;
int a;
for(i=0;i<6;i++) {
scanf("%d",&a);
m[i]=a;
}
k=0;
int v[2][3]; // this is where I pass the values from a array to a 2d array
for(i=0;i<2;i++) { // but for some reason it doesnt work
for(j=0;j<3;j++) {
v[i][j]=m[3*k+j]; // 3 is the maximum i value [n of your code]
}
k++;
}
return 0;
}
Just used OP's code and changed:
1) Defined all integer variables.
2) the int inside the for removed to be compatible code with every c compiler (OP doesn't really need this changes)
3) Added a variable k that been increased with the changes of outer loop variable and used it in the command v[i][j]=m[3*k+j]; to give the appropriate m value to the new array. (3 been explained in the comment of the same line)
See #Pablo's comment for not using k
Assuming you have at least as many elements in your 1D array as your 2D array and you want to fill in your 2D array in row major order, it suffices to just increment an index for your 1D array every time you read an element from it.
int v[n][b];
int k = 0;
for(int i=0;i<n;i++) {
for(int j=0;j<b;j++) {
v[i][j]=m[k++];
}
}
int main(void)
{
int a[5] = {36,24,10,6,12};
int pass;
int i;
int hold;
/* bubble sort */
/* loop to control number of passes */
for(pass=1; pass<5; pass++){
/* loop to control number of comparisons per pass */
for(i=0; i<5; i++){
if(a[i] > a[i+1]){
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}
return 0;
}
In this bubble sort program the if statement comparing adjacent element’s value.
If counter I becomes 4 then if statement would be if a[4] > a[4+1] so my question is there’s no a[5] element in the array so how program is comparing and doing work?
I don’t understood for(pass=1; pass<5; pass++) loop. What this loop work for? And why the loop starts from 1 and continues 4 times instead of 5.
Anybody please demonstrate how this bubble sort program is working? Cheers!
Well, everyone answered this in the comments, but noone took the time to write an actual answer, so I'd take the role.
1st thing first, the code you pasted has a Bug in it:
while the array int a[5] has 5 members [0..4],
when executing the inner loop for(i=0; i<5; i++) given i=4,
a[i+1] is accessing a[5] which is out of bounds of the array and it's value is probably unexpected.
Worth Noting: because the example values int a[5] = {36,24,10,6,12}; are very small, there is a high chance (36 / 2^32) that the code will work anyway because the a[5] will have the maximum value, and won't be overridden or moved.
but if you'd try changing the values to, lets say, int a[5] = {36,0xFFFFFFFF,10,6,12};, the program will surely fail miserably!
2nd to your other question:
with each iteration (pass), the maximum value is bubbled to it's place, and therefore will be in place...
for 5 numbers, after placing 4 in their place, the last one is given implicitly.
and that's why there is no need for the 5th iteration.
also, it is common in the 2nd to last iterations to exclude the last elements from the inner loop, as they are known to be in place.
int main(void)
{
int a[5] = {36,24,10,6,12};
int pass;
int i;
int hold;
/* bubble sort */
/* loop to control number of passes */
for(pass=4; pass > 0; pass--){ /* pass counts down 4 iterations */
/* loop to control number of comparisons per pass */
/* 0..4, then 0..3 > 0..2, and lastly 0..1 */
for(i=0; i<pass; i++){
if(a[i] > a[i+1]){
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}
return 0;
}
I am have a multi-dimensional array that needs to be resolved, to solve for the unknown values (x1,x2,x3,..). In this multi-dimensional array, my array size in the i and j coordinate are different; B[n][n+1]. I know this Basic C, Gauss Jordan Method to solve for the unknown, is incorrect and would like someone to point in how to modify it..
This code is accurate for an Array with the same n values only; eg. A[n][n].
//Computation to solve
for(j=0; j<=n; j++)
{
for(i=0; i<=n; i++)
{
if(i!=j)
{
c=B[i][j]/B[j][j];
for(k=0;k<=n+1;k++)
{
B[i][k] = B[i][k] - c*B[j][k];
}
}
}
}
//Print Solution
printf("\nThe solution is:\n");
for(i=0; i<=n; i++)
{
x[i]=B[i][n+1]/B[i][i];
printf("\n x%d=%.3f\n",i,x[i]);
}
An example would be if my n=2. The array that i would want to solve is B[2][3].
0 -20 0 -1
0 30 -10 0
0 -10 10 1
The output of this code is
x1= -inf
x2=0.050
x3=0.000
The correct output should be
x1=0.00
x2=0.05
x3=0.15
This code is accurate for an Array with the same n values only; eg.
A[n][n].
No, the code already accounts for column n+1 (which holds the right-hand constant terms) in the loop
for(k=0;k<=n+1;k++)
{
B[i][k] = B[i][k] - c*B[j][k];
}
(since k runs up to n+1). So, it is correct in this regard.
An example would be if my n=2. The array that i would want to solve is
B[2][3].
C arrays are declared by specifying the number of elements in the array, not the highest index, so you want B[3][4].
The main fault of the shown code is its lack of the row swapping operation, which may be necessary if B[j][j] is zero, and the related test. We can implement that by inserting
if (!B[j][j])
{
for (i=j+1; i<=n; i++)
if (B[i][j]) { swap(B[j], B[i]); break; }
if (!B[j][j]) continue; // leave all-zero column as is
}
at the beginning of the for(j=0; j<=n; j++) loop body (implementing swap() left to the reader).
The correct output should be
x1=0.00
Whether this is correct is debatable, but if you want a variable where every number is a solution to take the value zero, you may insert
if (B[i][i] == 0 && B[i][n+1] == 0) x[i] = 0;
before the printf("\n x%d=%.3f\n",i,x[i]).