Defining a matrix as an array of arrays and computation its inverse matrix in C++ - c++-cli

Unfortunately I haven't much experience in C++ and I'm trying to progress myself in C++.
Firstly,I defined array of arrays so that I formed an 3x3 matrix:
array< array< double >^ >^ input = gcnew array< array< double >^ >(3);
for (j=0;j<input->Length;j++){
input[j]=gcnew array<double>(3);
Then I assigned matrix elements to input array of arrays:
int value=1;
for(y=0;y<(3);y++){
for(x=0;x<(3);x++)
{input[y][x]=value;
value=value+1;
}
}
Is there a C++ function that compute inverse matrix of this input array of arrays?
Could you help me please?
Best Regards...

Look at Simple 3x3 matrix inverse code (C++).

There are no functions in C++ to make matrix operations, you'll need to find some library to do it or implement your own.
Note that for fixed size arrays, you can use regular C/C++ arrays, like this one:
double arr[3][3];

Wikipedia has a list of numerical libraries in various programming languages. If the functions that you are looking for are not available you could also consider writing a wrapper function around an available Fortran or C or C++ implementation.

There is not built in C++ function to do matrix inversion (or for any other matrix calculations).
There are lots of methods for matrix inversion mentioned HERE.
If you want efficiency and ease of implementation then Guassian Elimination is
probably the best.

Code for inverse of matrix using Elementary row transformation in c++
#include<iostream>
#include<stdio.h>
#include<conio.h>
using
namespace std;
float a[4][4];float b[4][4]={{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}};
int no = 4;
int check(int k) {
float cont = 0, cont2 = 0;
for (int i = k; i < no; i++) {
if (a[i][k] == 1) {
for (int j = 0; j < no; j++) {
cont = a[i][j];
cont2 = b[i][j];
a[i][j] = a[k][j];
b[i][j] = b[k][j];
a[k][j] = cont;
b[k][j] = cont2;
}
} else if (a[i][k] == 0) {
for (int j = 0; j < no; j++) {
cont = a[i][j];
cont2 = b[i][j];
a[i][j] = a[no - 1][j];
b[i][j] = b[no - 1][j];
a[no - 1][j] = cont;
b[no - 1][j] = cont2;
}
}
}
return 0;
}
int divi(int k) {
float particular = a[k][k];
for (int i = 0; i < no; i++) {
a[k][i] = a[k][i] / particular;
b[k][i] = b[k][i] / particular;
if (a[k][i] == (-0)) {
a[k][i] = 0;
}
if (b[k][i] == (-0)) {
b[k][i] = 0;
}
}
return 0;
}
int sub1(int k) {
float particular;
for (int j = k + 1; j < no; j++) {
particular = a[j][k];
for (int i = 0; i < no; i++) {
a[j][i] = a[j][i] - (particular * a[k][i]);
b[j][i] = b[j][i] - (particular * b[k][i]);
if (a[j][i] == (-0)) {
a[j][i] = 0;
}
if (b[j][i] == (-0)) {
b[j][i] = 0;
}
}
}
return 0;
}
int sub2(int k) {
float particular;
for (int j = k - 1; j >= 0; j--) {
particular = a[j][k];
for (int i = no - 1; i >= 0; i--) {
a[j][i] = a[j][i] - (particular * a[k][i]);
b[j][i] = b[j][i] - (particular * b[k][i]);
if (a[j][i] == (-0)) {
a[j][i] = 0;
}
if (b[j][i] == (-0)) {
b[j][i] = 0;
}
}
}
return 0;
}
int disp(){
cout<<endl;
for(int x=0;x<no;x++){
for(int y=0;y<no;y++){
if(a[x][y]==(-0)){a[x][y]=0;}
if(b[x][y]==(-0)){b[x][y]=0;}
printf("%0.1f|||%0.1f ",a[x][y],b[x][y]);
}
cout<<endl;}
}
int main()
{
for(int i=0;i<no;i++){
for(int j=0;j<no;j++){cout<<"Enter a["<<i<<"]["<<j<<"]";cin>>a[i}[j];}
}
for(int i=0;i<no;i++){
for(int j=0;j<no;j++){cout<<a[i][j]<<" ";}
cout<<endl;
}
for(int i=0;i<no;i++){
check(i);
disp();
divi(i);
disp();
sub1(i);
disp();
}
for(int i=no-1;i>=0;i--){
sub2(i);
disp();
cout<<endl;
}
getch();
getch();
getch();
return 0;}
}

Related

Objective-C equal distribution from 5 different NSMutableArrays

This is my code but its still not correct. Currently i can distribute like this: 0,1,2,0,1,2,0,1,2 but i will distribute it 0,1,2,2,1,0,0,1,2,2 (0,1,2 are the groups)
//Create x Groups
for (int z=0; z<numberOfGroups; z++) {
mutableArrayOfSubarrays[z] = [NSMutableArray arrayWithCapacity:countOfElementsForTheGroups];
}
int nextSubarray = 0;
//Distribute the Objects into the groups
for (int i = 0; i < [AllObjectsToDistribute count]; i++)
{
[mutableArrayOfSubarrays[nextSubarray] addObject:[AllObjectsToDistribute objectAtIndex:i]];
nextSubarray = nextSubarray % customGroups;
nextSubarray++;
nextSubarray = nextSubarray % customGroups;
}
Keep track of which way the group index counts in a BOOL.
Example:
NSUInteger groupIndex = 0;
BOOL groupIndexCountsUp = YES;
for (id object in allObjectsToDistribute) {
[groupsArray[groupIndex] addObject:object];
if (groupIndexCountsUp) {
if (groupIndex < numberOfGroups - 1)
groupIndex++;
else
groupIndexCountsUp = NO;
}
else {
if (groupIndex > 0)
groupIndex--;
else
groupIndexCountsUp = YES;
}
}

Detect break statement in function?

I have the function below:
- (void)doStuff {
BOOL allDoneNow = NO;
for (int i = 0; i < [arABFBmatches count]; i++) {
for (int j = 0; j < [arABFBmatches count]; j++) {
if (should_skip_rest) {
allDoneNow = YES;
break;
}
}
if (allDoneNow) break;
}
}
Now, if I call that method with [self doStuff];, how can I detect if the function broke? Or is there a better way to stop and restart the execution of a function?
- (BOOL)doStuff // <- return a boolean value
{
for (int i = 0; i < [arABFBmatches count]; i++)
{
for (int j = 0; j < [arABFBmatches count]; j++)
{
if (should_skip_rest)
{
return NO; // <- NO for break
}
}
}
return YES; // <- YES for completed
}
This beaks the execution of the function. If you want to restart it, simply call it in a while loop.
while( (doStuff()==NO) && thereShouldBeAnotherConditionForStopping )
{
// Do something after each attempt, otherwise it seems to be a little bit silly
}
Or you can use blocks, like this:
- (void)doStuff:(void (^)())breakBlock{
BOOL allDoneNow = NO;
for (int i = 0; i < [arABFBmatches count]; i++) {
for (int j = 0; j < [arABFBmatches count]; j++) {
if (should_skip_rest) {
allDoneNow = YES;
breakBlock();
break;
}
}
if (allDoneNow) breakBlock();
}
}
and call it:
[self doStuff:^{
NSLog(#"ends with break");
}];

Algorithm to find all possible solutions from an array of array

What is the best algorithm to find all possible words from an array of array of character.
Here an example :
From this array : [[A],[B,C,D],[E,F],[G,H]]
I need in return an array of the 12 ordered possibilities [[A,B,E,G],[A,C,E,G], ... , [A,D,F,H]]
Do you know how to implement this algorithm ? If you know it and you provide an example in any language (C,JAVA,Javascript, ...), feel free to share because it's been a day I try to find it ...
Here how I tries to implement it ("array" is an array of array of char):
+ (NSArray*) possibleReading:(NSMutableArray*)array {
int nbPossibilities = 1;
for(int i = 0; i < [array count]; i++) {
nbPossibilities *=[[array objectAtIndex:i] count];
}
NSMutableArray *possArr = [[NSMutableArray alloc] initWithCapacity:nbPossibilities];
for (int i=0; i < nbPossibilities; i++) {
NSMutableArray *innerArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
[possArr addObject:innerArray];
}
for (int i=0; i< [array count]; i++) {
//
for(int nbPoss = 0; nbPoss < nbPossibilities; nbPoss++) {
NSMutableArray * arr = [possArr objectAtIndex:nbPoss];
NSNumber * num = [NSNumber numberWithInt:nbPoss % [[array objectAtIndex:i] count]];
NSString * literal = [[array objectAtIndex:i] objectAtIndex:[num intValue]];
[arr insertObject:literal atIndex:i];
}
}
return possArr;
}
It would be easiest to do this using a recursive method.
Java code
import java.util.Arrays;
public class CartesianProductCalculator {
private char[][] result;
private char[][] sets;
private char[] currentSet;
private int index;
public char[][] calculateProduct(char[][] sets) {
index = 0;
// calculate size of result
int resultSize = 1;
this.sets = sets;
for (char[] set : sets) {
resultSize *= set.length;
}
result = new char[resultSize][];
currentSet = new char[sets.length];
calculateProduct(sets.length-1);
return result;
}
// fills result from right to left
public void calculateProduct(int setIndex) {
if (setIndex >= 0) {
for (char c : sets[setIndex]) {
currentSet[setIndex] = c;
calculateProduct(setIndex-1);
}
} else {
result[index++] = Arrays.copyOf(currentSet, currentSet.length);
}
}
public static void main(String[] args) {
char[][] input = {{'A'},{'B','C','D'},{'E','F'},{'G','H'}};
CartesianProductCalculator productCalculator = new CartesianProductCalculator();
System.out.println(Arrays.deepToString(productCalculator.calculateProduct(input)));
}
}
Objectiv-C
+ (NSArray *) cartesianProductOfArrays(NSArray *arrays) {
int arraysCount = arrays.count;
unsigned long resultSize = 1;
for (NSArray *array in arrays)
resultSize *= array.count;
NSMutableArray *product = [NSMutableArray arrayWithCapacity:resultSize];
for (unsigned long i = 0; i < resultSize; ++i) {
NSMutableArray *cross = [NSMutableArray arrayWithCapacity:arraysCount];
[product addObject:cross];
unsigned long n = i;
for (NSArray *array in arrays) {
[cross addObject:[array objectAtIndex:n % array.count]];
n /= array.count;
}
}
return product;
}
C
#include <stdio.h>
#include <string.h>
void print(int size, char *array[size], int indexs[size]){
char result[size+1];
int i;
for(i = 0; i < size; ++i)
result[i] = array[i][indexs[i]];
result[size] = 0;
puts(result);
}
int countUp(int size, int indexs[size], int lens[size]){
int i = size -1;
while(i >= 0){
indexs[i] += 1;// count up
if(indexs[i] == lens[i])
indexs[i--] = 0;
else
break;
}
return i >= 0;
}
void find_all(int size, char *array[size]){
int lens[size];
int indexs[size];
int i;
for(i = 0; i < size; ++i){//initialize
lens[i] = strlen(array[i]);
indexs[i] = 0;
}
do{
print(size, array, indexs);
}while(countUp(size, indexs, lens));
}
int main(void){
char *array[] = { "A", "BCD", "EF", "GH" };
int size = sizeof(array)/sizeof(*array);
find_all(size, array);
return 0;
}
If you can remove duplicate entries in inner array objects before executing method then you won't get duplicate words in result array.
- (NSArray*) possibleReading:(NSMutableArray*)array {
int nbPossibilities = 1;
for(int i = 0; i < [array count]; i++)
{
NSArray *cleanedArray = [[NSSet setWithArray:[array objectAtIndex:i]] allObjects];
[array replaceObjectAtIndex:i withObject:cleanedArray];
nbPossibilities *=[[array objectAtIndex:i] count];
}
NSMutableArray *possArr = [[NSMutableArray alloc] initWithCapacity:nbPossibilities];
for (int i=0; i < nbPossibilities; i++) {
NSMutableArray *innerArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
[possArr addObject:innerArray];
}
for (int i=0; i< [array count]; i++) {
//
for(int nbPoss = 0; nbPoss < nbPossibilities; nbPoss++) {
NSMutableArray * arr = [possArr objectAtIndex:nbPoss];
NSNumber * num = [NSNumber numberWithInt:nbPoss % [[array objectAtIndex:i] count]];
NSString * literal = [[array objectAtIndex:i] objectAtIndex:[num intValue]];
[arr insertObject:literal atIndex:i];
}
}
return possArr;
}

Why does my sorted array occasionally return random 0s at the end?

I wrote a program to sort a randomly generated array of 50 integers from greatest to least. So far it works, but it will occasionally return random zeros at the end of the sorted array. These zeros are not present in the unsorted array, and they do not always appear. Here's my program:
#import <Foundation/Foundation.h>
#interface Number: NSObject
- (void) start;
- (int) getValue;
- (void) counted;
- (void) placeValue: (int) a;
#end
#implementation Number
{
int x;
}
- (void) start
{
x = arc4random_uniform(1000);
if (x == 1)
{
x = x+1;
}
}
- (int) getValue
{
return x;
}
- (void) counted
{
x = 0;
}
- (void) placeValue: (int) a
{
x = a;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool
{
NSMutableArray *unsortedArray = [[NSMutableArray alloc] initWithCapacity: 50];
for (int n = 0; n < 50; n++)
{
Number *num = [[Number alloc] init];
[num start];
[unsortedArray addObject: num];
}
for (int n = 0; n < 50; n++)
{
printf("%i, ", [unsortedArray[n] getValue]);
}
printf ("unsorted array.\n\n");
int x = 0;
int y = 1001;
for (int n = 0; n < 50; n++)
{
for (int m = 0; m < 50; m++)
{
if (([unsortedArray[m] getValue] > x) && ([unsortedArray[m] getValue] < y))
{
x = [unsortedArray[m] getValue];
}
}
printf("%i, ", x);
y = x;
x = 0;
}
printf("sorted array.\n");
} return 0;
}
Try this:
- (void)start
{
x = (arc4random_uniform(1000) + 1);
}
You don't want to only be increasing x when you hit 0 or 1, since that will skew the results. arc4random_uniform will return a random number less than 1000 in this case, so 0 -> 999, adding 1 to all values, gives you 1 -> 1000. Adjust your numbers to suit what you need.
There are other issues in your code though. Why create your own Number class? Why create your own sort method? Use NSNumber and NSArray's sort methods.
Here is a much cleaner version:
int main(int argc, const char * argv[])
{
#autoreleasepool
{
NSMutableArray* unsortedArray = [[NSMutableArray alloc] initWithCapacity:50];
for (NSUInteger n = 0; n < 50; ++n) {
[unsortedArray addObject:#(arc4random_uniform(999) + 1)];
}
for (NSUInteger n = 0; n < 50; ++n) {
printf("%li, ", (long)[unsortedArray[n] integerValue]);
}
printf ("unsorted array.\n\n");
NSArray* sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
for (NSUInteger n = 0; n < 50; ++n) {
printf("%li, ", (long)[sortedArray[n] integerValue]);
}
printf("sorted array.\n");
}
return 0;
}
- (void) start
{
x = arc4random_uniform(1000);
if (x == 0)
x = x + 1;
}
Everyone is focusing on the fact that arc4random_uniform can generate zero as an acceptable value (which is true), but there is another problem: Your sort algorithm is incorrect, as it will only work if the values in the array are unique. But, if you have any duplicate values (and there's no assurances that arc4random_uniform won't generate some duplicates), your algorithm will show only one of those values, and thus, by the time you get to the end, you'll see a bunch of extra zeros.
There are tons of different sorting algorithms, but it's probably easier to just avail yourself of one of the native NSMutableArray sort methods, which gets you out of the weeds of writing your own.

Dynamic two dimensional C array crashing in Objective-C

I am making a curve fitting program using matrices in the form of a two dimensional arrays but the compiler throws out BAD_ACCESS errors at random such as Thread 1:EXC_BAD_ACCESS (code=1, address=0x13f800000). The program works sometimes and other times crashes. Any ideas would be appreciated. Thanks.
- (void)main {
NSLog(#"Enter size");
scanf("%i", &matrixSize);
float* temp;
matrix = (float**)calloc(matrixSize, sizeof(float*));
temp = (float*)calloc(matrixSize+1, sizeof(float));
for (int i = 0; i < matrixSize+1; i++) {
matrix[i] = temp + (i*(matrixSize+1));
}
[self enterPoints];
[self elimination];
[self setNeedsDisplay:YES];
free(matrix);
free(temp);
}
//points entered here
- (void)enterPoints {
CGPoint *points = (CGPoint *)malloc(matrixSize * sizeof(CGPoint));
for (int i = 0; i < matrixSize; i++) {
scanf("%lf", &points[i].x);
scanf("%lf", &points[i].y);
}
for (int j = 0; j < matrixSize; j++) {
for (int i = 0; i < matrixSize+1; i++) {
if (i == (matrixSize)) {
matrix[i][j] = points[j].y;
}
else {
matrix[i][j] = pow(points[j].x, (matrixSize-1)-i);
}
}
}
free(points);
}
//matrix reduction occurs here
- (void)elimination {
for (int j = 0; j < matrixSize; j++) {
double divideValue = matrix[j][j];
for (int i = 0; i < matrixSize+1; i++) {
matrix[i][j] /= divideValue;
}
for (int j1 = 0; j1 < matrixSize; j1++) {
if (j1 == j) {
if (j1 == matrixSize-1) {
break;
}
else {
j1++;
}
}
double subValue = matrix[j][j1];
for (int i = 0; i < matrixSize+1; i++) {
matrix[i][j1] -= matrix[i][j]*subValue;
}
}
}
}
//drawing the polynomial
- (void)drawRect:(NSRect)dirtyRect {
NSGraphicsContext * GraphicsContext = [NSGraphicsContext currentContext];
CGContextRef context = (CGContextRef) [GraphicsContext graphicsPort];
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
CGContextSetLineWidth(context, 3.0);
CGContextMoveToPoint(context, 0, matrix[matrixSize][0]*100 + 100);
[GraphicsContext saveGraphicsState];
CGMutablePathRef path;
path = CGPathCreateMutable();
for (float i = -matrixSize; i < matrixSize; i+=.01) {
float y = 0;
for (int j = 0; j < matrixSize; j++) {
y += matrix[matrixSize][j]*pow(i, j);
}
CGContextAddLineToPoint(context, i*100 + 100, y*100 + 100);
}
CGContextStrokePath(context);
[GraphicsContext restoreGraphicsState];
}
You did not allocate enough memory for your matrix. This line sets up the entire data area, but you have only allocated matrixSize+1 elements, instead of matrixSize*(matrixSize+1):
temp = (float*)calloc(matrixSize+1, sizeof(float));
So, maintaining the matrixSize+1 columns and matrixSize rows:
matrix = (float**)calloc(matrixSize, sizeof(float*));
temp = (float*)calloc(matrixSize * (matrixSize+1), sizeof(float));
for (int i = 0; i < matrixSize; i++) {
matrix[i] = temp + (i*(matrixSize+1));
}
When you use this later, be careful. You are addressing it wrong:
for (int j = 0; j < matrixSize; j++) {
for (int i = 0; i < matrixSize+1; i++) {
if (i == (matrixSize)) {
matrix[i][j] = points[j].y;
}
else {
matrix[i][j] = pow(points[j].x, (matrixSize-1)-i);
}
}
}
Notice that i goes to matrixSize+1 but you are using that as the row index (there are only matrixSize rows). I think you meant to use matrix[j][i] instead of matrix[i][j]. You also do this when you construct the initial matrix, but I've actually changed that to be in line with your allocation.
So there are two points of buffer overrun in your program that I see.
EXC_BAD_ACCESS indicates one of your objects is being over-released (not to be confused with garbage collection) before invoking a method on it. Once you reach the point in your code where you invoke the method on the collected object, the pointer is referencing an invalid memory location.
To find Zombie objects have a look at this: How to Enable NSZombie in XCode
I've used this and it works very well.