Let k[i] is a strictly increasing data and
A=Table[k[i],{i,1,30}];
B=List[k[1],k[3],k[4],k[7],k[10],k[12],k[17],k[18],k[19],k[23],k[26]];
Now I would like to get what is the index for B[n], for example B[4]=A[7], and my question is to get 7. I tried InverseFunction,
InverseFunction[A][B[4]]
but it does not work. A similar question arise when I define A and B by the following sets
A=List[k[1],k[2],k[3],k[4],k[5],k[6],k[7],k[8],k[9],k[10],k[11],k[12],k[13],k[14],k[15]];
B=List[k[1],k[3],k[4],k[7],k[10],k[12],k[14]];
If the problem is in the method of representing data by the function List, please let me know a better way.
Related
Have a function Arr(strArr) read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers. For example of strArr is ["[1, 2, 5, 6]", "[5, 2, 8, 11]"], and goal for this is to add the elements in corresponding locations from both arrays. For the example input, the program should do the following additions: [(1 + 5), (2 + 2), (5 + 8), (6 + 11)] which then equals [6, 4, 13, 17]. Return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17.
If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array.
Examples
Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
Output: 7-4-6-10-6
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"]
Output: 3-3-6-2
Thank you for your help.
The question seems obviously a homework exercise, and as was pointed out in comments that's not what StackOverflow is for; however, I know a lot of students who struggle to know even how to approach a problem. I think helping with that is a good thing, so I won't give a solution to the problem, but rather advice about approaching it.
The general formula that works for most problems is simple: Break the problem into smaller sub-problems, and solve each of those independently, then combine the sub-solutions. If any of those sub-problems are too complicated, repeat the process for those, and so on.
Homework problems, and a lot of real world problems, usually break down into three main sub-problems:
Transform some input into a more conveniently computable form.
Process the transformed input into some computed outputs.
Transform the computed outputs into a specified format.
Applied to your problem, you have:
How to parse a specially formatted string into an array of integers.
How to sum corresponding elements of two arrays, taking into account they may be of different lengths, to produce an array of sums.
How to transform an array of integers into a specially delimited string output.
The solution to your top-level problem will involve applying the sub-solutions in that order, but you don't have to solve them in that order. If you're having difficulty with getting started with the first one, solve one of the easier sub-solutions first to get some momentum. Psychology is actually quite important in problem solving. Believing you can solve it is half of actually solving it, so solve the easier problems first to get that factor working in your favor.
Maybe you regard the sub-problem 3 as the easiest to solve: So write a function place-holder for it (aka, a "stub function"), and make up some input data to test it. This would lead you to write something like this:
func formatOutput(from intArray: [Int]) -> String
{
// Your implementation will go here
}
let actual = formatOutput(from: [1, 2, 3, 4])
let expected = "1-2-3-4"
// If you're doing this in a playground, app, or command line tool
if actual != expected {
fatalError("FAILED: \"\(actual)\" != \"\(expected)\"")
}
else { print("Yay! Passed!") }
// If you're using XCTest
XCTAssertEqual(actual, expected)
That won't even compile yet, because formatOutput has to return something, and it doesn't yet. The key thing is that you've written your usage code first, and expressed in code what you expect. Now focus on the guts of formatOutput. If you want to take a Test Driven Development approach (TDD), maybe at first just return an empty string from formatOutput so you can be sure the code compiles and you see a failing test. Then implement it correctly if you know how, or in small steps if you're not clear on what to do. As you get the exact thing you're testing for working, you can keep adding more tests and improving formatOutput until you've verifiably got it doing everything it's supposed to do. Remember the KISS principle: "Keep It Simple, Stupid!" Don't over-think the solution, and save doing it "cleverly" for another day, which often never comes because the simple thing was sufficient.
At that point you have one of the sub-problems solved, so you move on to the next, following the same pattern. And the next, until all the parts are solved. Then put them together.
You'll note that sub-problem 2 has a bit of an extended description, especially the part specifying that the arrays may be of different lengths. Unless you already know how to solve that problem as stated, that sort of thing indicates it's a good candidate to be broken into yet simpler problems:
2a. How to sum corresponding elements of two arrays of the same length.
2b. How to modify 2a to handle arrays of different lengths.
2b can be done a few different ways:
2.b.1. Apply 2.a to sub-arrays of common length, then handle the remaining part of the longer one separately
OR
2.b.2. Enlarge the shorter array so that it is the same length as the longer one, so 2.a can be applied unmodified.
OR
2.b.3. Modify 2.a so that it can treat the shorter array as though it were the same length as the longer one, without actually copying or adding new elements.
OR
2.b.4. Modify 2.a so that it doesn't have to do anything special for different lengths at all. Hint: think more about the output and its length than the inputs.
When faced with alternatives like that, in the absence of any external constraints that would make one option preferred over the others, pick the one that seems simplest to you (or the most interesting, or the one you think you'd learn the most from). Or if you have time, and want to get the most out of the exercise, implement all of them so you can learn how they are all done, and then pick the one you like best for your final code.
func getResult(strArr: [String]) -> String {
let intArray1 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[0].utf8))) ?? []
let intArray2 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[1].utf8))) ?? []
var arrayResult = zip(intArray1,intArray2).map(+)
let commonCount = arrayResult.count
arrayResult.append(contentsOf: intArray1.dropFirst(commonCount))
arrayResult.append(contentsOf: intArray2.dropFirst(commonCount))
return arrayResult.map(String.init).joined(separator: "-")
}
let result1 = getResult(strArr : ["[5, 2, 3]", "[2, 2, 3, 10, 6]"])
let result2 = getResult(strArr : ["[1, 2, 1]", "[2, 1, 5, 2]"])
You can use this function to get your desired result.
EDIT
SOLVED
Solution was to use the long double versions of sin & cos: sinl & cosl.
It is my first post here, so bear with me :).
I come today here to ask for your input on a small problem that I am having with a C application at work. Basically, I am computing an Extended Kalman Filter and one of my formulas (that I store in a variable) has multiple computations of sin and cos, at least 16 in total in the same line. I want to decrease the time it takes for the computation to be done, so the idea is to compute each cos and sin separately, store them in a variable, and then replace the variables back in the formula.
So I did this:
const ComputationType sin_Roll = compute_sin((ComputationType)(Roll));
const ComputationType sin_Pitch = compute_sin((ComputationType)(Pitch));
const ComputationType cos_Pitch = compute_cos((ComputationType)(Pitch));
const ComputationType cos_Roll = compute_cos((ComputationType)(Roll));
Where ComputationType is a macro definition (renaming) of the type Double. I know it looks ugly, a lot of maybe unnecessary castings, but this code is generated in Python and it was specifically designed so....
Also, compute_cos and compute_sin are defined as such:
#define compute_sin(a) sinf(a)
#define compute_cos(a) cosf(a)
My problem is the value I get from the "optimized" formula is different from the value of the original one.
I will post the code of both and I apologise in advance because it is very ugly and hard to follow but the main points where cos and sin have been replaced can be seen. This is my task, to clean it up and optimize it, but I am doing it step by step to make sure I don't introduce a bug.
So, the new value is:
ComputationType newValue = (ComputationType)(((((((ComputationType)-1.0))*(sin_Pitch))+((DT)*((((Dg_y)+((((ComputationType)-1.0))*(Gy)))*(cos_Pitch)*(cos_Roll))+(((Gz)+((((ComputationType)-1.0))*(Dg_z)))*(cos_Pitch)*(sin_Roll)))))*(cos_Pitch)*(cos_Roll))+((((DT)*((((Dg_y)+((((ComputationType)-1.0))*(Gy)))*(cos_Roll)*(sin_Pitch))+(((Gz)+((((ComputationType)-1.0))*(Dg_z)))*(sin_Pitch)*(sin_Roll))))+(cos_Pitch))*(cos_Roll)*(sin_Pitch))+((((ComputationType)-1.0))*(DT)*((((Gz)+((((ComputationType)-1.0))*(Dg_z)))*(cos_Roll))+((((ComputationType)-1.0))*((Dg_y)+((((ComputationType)-1.0))*(Gy)))*(sin_Roll)))*(sin_Roll)));
And the original is:
ComputationType originalValue = (ComputationType)(((((((ComputationType)-1.0))*(compute_sin((ComputationType)(Pitch))))+((DT)*((((Dg_y)+((((ComputationType)-1.0))*(Gy)))*(compute_cos((ComputationType)(Pitch)))*(compute_cos((ComputationType)(Roll))))+(((Gz)+((((ComputationType)-1.0))*(Dg_z)))*(compute_cos((ComputationType)(Pitch)))*(compute_sin((ComputationType)(Roll)))))))*(compute_cos((ComputationType)(Pitch)))*(compute_cos((ComputationType)(Roll))))+((((DT)*((((Dg_y)+((((ComputationType)-1.0))*(Gy)))*(compute_cos((ComputationType)(Roll)))*(compute_sin((ComputationType)(Pitch))))+(((Gz)+((((ComputationType)-1.0))*(Dg_z)))*(compute_sin((ComputationType)(Pitch)))*(compute_sin((ComputationType)(Roll))))))+(compute_cos((ComputationType)(Pitch))))*(compute_cos((ComputationType)(Roll)))*(compute_sin((ComputationType)(Pitch))))+((((ComputationType)-1.0))*(DT)*((((Gz)+((((ComputationType)-1.0))*(Dg_z)))*(compute_cos((ComputationType)(Roll))))+((((ComputationType)-1.0))*((Dg_y)+((((ComputationType)-1.0))*(Gy)))*(compute_sin((ComputationType)(Roll)))))*(compute_sin((ComputationType)(Roll)))));
What I want is to get the same value as in the original formula. To compare them I use memcmp.
Any help is welcome. I kindly thank you in advance :).
EDIT
I will post also the values that I get.
New value : -1.2214615708217025e-005
Original value : -1.2214615708215651e-005
They are similar up to a point, but the application is safety critical and it is necessary to validate the results.
You can not meet your expectation for a couple of reasons.
By altering the code you adjust the machine instructions being used in subtle ways that will impact the final value.
For instance if originally it was using fused multiplies and adds and this is no longer happening it will change the result.
You don't mention the target architecture. Some architectures retain more than 64bits in the floating point pipeline. These extra bits get rounded when forced into 64bit memory. Again altering how this works will have minor effects on the final output.
I'm looking for an elegant way of useing ndgrid and interpn in a more "general" way - basically for any given size of input and not treat each rank in a separate case.
Given an N-D source data with matching N-D mesh given in a cell-array of 1D vectors for each coordinate Mesh={[x1]; [x2]; ...; [xn]} and the query/output coordinates given in the same way (QueryMesh), how do I generate the ndgrid matrices and use them in the interpn without setting a case for each dimension?
Also, if there is a better way the define the mesh - I am more than willing to change.
Here's a pretty obvious, conceptual (and NOT WORKING) schematic of what I want to get, if it wasn't clear
Mesh={linspace(0,1,10); linspace(0,4,20); ... linsapce(0,10,15)};
QueryMesh={linspace(0,1,20); linspace(0,4,40); ... linsapce(0,10,30)};
Data=... (whatever)
NewData=InterpolateGeneric(Mesh,QueryMesh,Data);
function NewData=InterpolateGeneric(Mesh,QueryMesh,Data)
InGrid=ndgrid(Mesh{:});
OutGrid=ndgrid(QueryMesh{:});
NewData=interpn(InGrid{:},Data,OutGrid{:},'linear',0.0)
end
I think what you are looking for is how to get multiple outputs from this line:
OutGrid = ndgrid(QueryMesh{:});
Since ndgrid produces as many output arrays as input arrays it receives, you can create an empty cell array in this way:
OutGrid = cell(size(QueryMesh));
Next, prove each of the elements of OutGrid as an output argument:
[OutGrid{:}] = ndgrid(QueryMesh{:});
I am trying to create an ADT.
It is a dynamic set of finite elements. It must be implemented using arrays and linked lists.
Some operations include add(set, x) and remove(set, x).
I understand that I first need to create an interface which will be common to both the array implementation and the linked list implementation.
I am however, not sure as regards the structure for this data type. What should I include?
struct test {
int x;
char y;
};
Something like that? Or let's say that I make the set exclusive for integers, what will the data structure involve?
Help would be greatly appreciated. Thanks!
Since this is for school, I'm not going to give you an implementation, but I'll point you in the right direction. Using arrays and lists screams 'hash table'. See this answer for some good information.
For simplicity, let's assume it's a set of integers.
Essentially, you want an array hash_table of N 'buckets', i.e. lists. To add an element x, you do hash_table[hash(x) % N] to get the 'bucket' (list) x should go into, and add it to that list if it's not already in the list.
To remove x, do hash_table[hash(x) % N] to get your bucket, and remove x if it's there.
If you can implement those, search(set, x) is trivial. You can also try implementing union(setA, setB), intersect(setA, setB), difference(setA, setB), isSubset(setA, setB), etc. You may also want to peruse the Wikipedia article on the Set ADT, and do check out the entry in The Algorithm Design Manual which includes links to implementations at the bottom.
Good luck, and happy coding. If you get stuck it's always OK to ask here on SO, just post code next time. :)
This is the principle of a structure, you can put all type of variable you want in it ..
I think you want to create an array of int.
Declaring like :
int tab["number of int you want"];
And access it like that :
tab["number of case of the int you want to access"];
The question is in the title: does mxDestroyArray() recursively destroy elements of cells and structs? Is is about MATLAB's C matrix library interface.
To explain in more detail through a concrete example, suppose that I create a 1 by 1 cell using mxCreateCellArray(), then create a numeric matrix using mxCreateNumericArray() and set it as the only element of the cell. Now will calling mxDestroyArray() on the cell destroy the numeric array as well, in one go? Or do I need to call it separately for the numerical array, then the cell? I am hoping for the latter, as this is more reasonable for complex manipulations.
The documentation is ambiguous on this point. Also, it's not easy to devise a test that would give a definitive answer to this.
According to the reply I got on MATLAB answers, mxDestroyArray() does free elements of cells and structs recursively. Please see that answer for an example program that confirms this.