w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Solving nonlinear minimization equations symbolically in matlab
The problem you seem to run into is that there is no solution, not even matlab can deal with that. Try it like this: myMin = -6; syms x y S=solve(... x²-4==0,... y²-9==0,... x*y==myMin,... x+y==myMin + 5); %Note the +5 to make it feasible Cannot try myself, but a quick calculation tells me that this one is at least solvable.

Categories : Matlab

Solving a simple non-linear equation in Matlab
I assume that x is a symbolic variable, while the vector z is numeric? So, something like this: syms x y; z = 1:5; solve(exp(x*max(z))/sum(exp(x*z))==y,x) which returns Warning: The solutions are parametrized by the symbols: z1 = RootOf(y*z^4 - z^4 + y*z^3 + y*z^2 + y*z + y, z) > In solve at 180 ans = log(z1) solve does give you a solution, just not an explicit one. It tells you that you have several solutions that are the roots of some polynomial. The more elements that z has (and depending on the specific values of z) the higher the order the polynomial will be. The roots of quadratics and cubics are easily found. Quartics (with constant coefficients) can also be factored. Some quintics can be too, but for higher orders, there are very few known analytical solutions for

Categories : Matlab

Solving nonlinear least-squares problems in Excel VBA
This question will probably get a better response on SuperUser, but here's a possible solution: In Excel, if you create a Scatter chart of your data, you can right-click on the line in the chart, and choose 'Add Trendline'. This will give you several options for the type ofcurve-fitting you want to do. However, all the built-in methods are for 'linear' data and will most likely not be optimal for non-linear data.

Categories : Excel

Solving Nonlinear curve fit to current code
In general, truly fitting a non-linear curve is a very difficult problem (mostly because the solution space is infinite and non-continuous), but in general scipy is where you're going to want to look for solutions to this kind of problem. If you know the general form of the equation you can apply a transform to it and use a poly-fit algorithm (still infinite, but continuous) to try fitting it. For that look here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html Certainly for an exponential curve this could be used pretty trivially by taking the logarithm of your data. If you want to really try optimizing some arbitrary least-squares fit you have to stop thinking of curve-fitting and start thinking of multi-variable optimization. Again, scipy is where you should loo

Categories : Python

number of solution to nonlinear congruence equation
Yes if x^a mod b = c then (x+b)^a mod b = c. So there would be a total of 1 + floor((u-x)/b) solutions thus far. You just have to remember to skip those numbers while you are searching for other solutions from (x+1) to min(u,b). The concept works for 2 variables but much more computationally intensive. You solve x^a mod b = d and save the count as T[d] where 0 ≤ d < b. You might ask why 0 ≤ d < b and not 0 ≤ d ≤ c. This example is why: if c=7 and b=35 then (x,y) such that x^a mod 35 = 8 and y^a mod 35 = -1 ≡ 34 would be a solution as well. Then the total number of solutions is similar to what you suggested except I don't bother with separate handling of x=y and x≠y: for (i=0 ; i < b ; i++) count += T[i]*T[(b +c -i)%b];

Categories : Algorithm

Solving nonlinear optimization equations with large errors
Based on your comment and example I think you are simply looking for this: x = -10:0.1:10 %Suppose this is your x y = max(min(x,5),3) %Force it between 3 and 5 by rounding up or down respectively

Categories : Matlab

Solving equation in Python 3.3
Y, C, m, and d are all strings. You want to convert them into ints first: Y = int(f[2:4]) C = int(f[:2]) ... Are you sure that equation even works, though? It looks like it'd produce a lot of non-integer weekdays. You might've miscopied it. Also, brackets aren't a grouping operator in Python; they're the list construction syntax. You'll want to replace those brackets with parentheses in the expression for w. (Or were those brackets supposed to be the floor operator? If so, you'll want math.floor, from the math module, or just int if truncation is fine.)

Categories : Python

Solving an equation with Sympy symbols
You could use nsolve to solve a problem like this -- but you need a guess as to where the solution(s) might be: >>> for n in range(5, 10): ... print 'n = %3d' % n ... denominator = (1 + Wmin + p * Wmin * ((1 - (2 * p) ** m) / (1 - 2 * p))) ... right = 1 - (1 - 2 / denominator) ** (n - 1) ... p_solve = nsolve(sympy.Eq(p, right),p,0) ... print p_solve ... n = 5 0.181881594898608 n = 6 0.210681675044646 n = 7 0.235278433487669 n = 8 0.256480923202426 n = 9 0.27492972759045

Categories : Python

Solving a simple sparse linear system of equation using csparse: cs_cholsol
Having never worked with csparse before, I skimmed the source code. When you call cs_spalloc() to create Operator, you are creating a triplet (indicated by setting the last parameter to 1). But, after the call to cs_copmress(), the result is no longer a triplet (you can detect this by checking the result and see that Operator->n is now -1 after compression). So, it is an error to traverse the matrix as if it were. You can use the cs_print() API to print your sparse matrix. As an aside, your code leaks memory, since the compressed matrix is a new allocation, and the original uncompressed matrix was not freed by cs_compress().

Categories : C++

Allowing for some Nonlinear Constraint Violations in Matlab
Firstly, adding some randomness to the constraint function is a bad plan - the optimiser has no chance... it will think it has found something close to a solution, and next time it tries something close to it, the solution will have completely changed. You're right that it will hurt the convergence of the optimiser if you have a single function that returns the proportion of constraints that are satisfied, because it will not be smooth - it is a discrete function that will jump in steps. Furthermore, you're effectively hiding useful information from the optimiser, because it doesn't know how individual constraints are affected by the solution parameters. I suggest you add an additional unknown, say conval, and instead of testing whether the constraints are <0, test whether they are l

Categories : Matlab

Solving polynomial 3rd order polynomial equation for intensity mapping
Not sure if this is what you need, but try this simple approach, which uses the [-10,10) values range for x,y and z: class Program { static void Main(string[] args) { int x = 0, y = 0, z = 0; int x1 = -10, x2 = 10, y1 = -10, y2 = 10, z1 = -10, z2 = 10; for (int ix = x1; ix < x2; ix++) { for (int iy = y1; iy < y2; iy++) { for (int iz = z1; iz < z2; iz++) { var result = (2 * ix) + (5 * iy) + 6 * (Math.Pow(iz, 2)); if (result > 0) { Console.WriteLine("x {0} y {1} z {2} : {3}", ix, iy, iz, result); } } }

Categories : C#

Using a value from a matrix as a multiplier in an equation?
In MATLAB, apostrophes ('') define a string. If the name of your matrix is answer, you can refer to its second value by the command answer(2) as mentioned by @Schorsch. For more infos on vectors and matrices, you can check this site.

Categories : Matlab

Sudoku solving matrix, while statement gives an infinite loop
You are using assignment =, instead of equality == here: while(a[i][k]=99||a[i][k]=0) ^ ^ this should be: while(a[i][k]==99||a[i][k]==0) a[i][k]=99 will always evaluate to true since 99 is non-zero, although your original code does not compile for me under gcc as it is, so I suspect the code you are running either has some parenthesizes or is slightly different. Also using k in the while loop before it is initialized is undefined behavior and it is unclear that your termination logic makes sense for a k that is constantly changing for each loop iteration. Another source of the infinite loop is inputvalue which seems to get stuck returning 0 in some instances, so you need to tweak that a bit to prevent infinite loops. Also, srand(time(NULL)); is a more c

Categories : C++

What is the fastest method for solving exp(ax)-ax+c=0 for x in matlab
Just wanting something to run more quickly is insufficient for that to happen. And, sorry, but if fzero is not fast enough then you won't do much better for a general root finding tool. If you aren't using fzero, then why not? After all, that IS the built-in solver you did not name. (BE EXPLICIT! Otherwise we must guess.) Perhaps you are using solve, from the symbolic toolbox. It will be more slow, since it is a symbolic tool. Having said the above, I might point out that you might be able to improve by recognizing that this is really a problem with a single parameter, c. That is, transform the problem to solving exp(y) - y + c = 0 where y = ax Once you know the value of y, divide by a to get x. Of course, this way of looking at the problem makes it obvious that you have made an

Categories : Matlab

Write Equation from Fit in Legend, Matlab
The documentation explains that you can obtain the coefficients derived from a fit executed as c = fit(...), as coef=coeffvalues(c) C=coef(1) x=coef(2) You can create your own legend as illustrated by the following example. Defining C and x as the parameters from your fits, % simulate and plot some data t= [0:0.1:1]; C = 0.9; x = 1; figure, hold on plot(t,C*exp(-x*t)+ 0.1*randn(1,length(t)),'ok', 'MarkerFaceColor','k') plot(t,C*exp(-x*t),':k') axis([-.1 1.2 0 1.2]) % here we add the "legend" line([0.62 0.7],[1 1],'Linestyle',':','color','k') text(0.6,1,[ ' ' num2str(C,'%.2f'),' exp(-' num2str(x,'%.2f') ' t) ' ],'EdgeColor','k') set(gca,'box','on') Example output: You may have to adjust number formatting and the size of the text box to suit your needs.

Categories : Matlab

Finding the equation of a contour in Matlab
From doc contour: [C,H] = CONTOUR(...) returns contour matrix C as described in CONTOURC and a handle H to a contourgroup object. This handle can be used as input to CLABEL. And from contourc: The contour matrix C is a two row matrix of contour lines. Each contiguous drawing segment contains the value of the contour, the number of (x,y) drawing pairs, and the pairs themselves. The segments are appended end-to-end as C = [level1 x1 x2 x3 ... level2 x2 x2 x3 ...; pairs1 y1 y2 y3 ... pairs2 y2 y2 y3 ...]

Categories : Matlab

MATLAB - lsqnonlin for equation systems
Using lsqnonlin makes sense ; Considering documentation notations (http://www.mathworks.fr/fr/help/optim/ug/lsqnonlin.html), the functions are the following : f1 = sqrt( (E-x)^2 + (F-y)^2 ) + sqrt( (G-x)^2 + (H-y)^2 ) + p - A(B-C-D) f2 = sqrt( (L-x)^2 + (M-y)^2 ) - sqrt( (N-x)^2 + (O-y)^2 ) + p - A(I-J-K) Solver will minimize f1^2 + f2^2. Of course, you can add additional equations, but they will not be considered as hard constraints. If you want your solution to enforce constraints, you should be able to do it with fsolve. Cheers

Categories : Algorithm

Changing values in one MatLab matrix based on ranges stored in a second matrix
How about replacing everything with: vals = sparse(triggerIndices, 1, increment, numel(sourceData), 1); vals(triggerIndices(1)) = addOn; sourceData(:) = sourceData(:) + cumsum(vals); This is basically a variant of run-length decoding shown here.

Categories : Matlab

octave/matlab: create new matrix based on existence of words from one matrix in another
Easily with a for-loop: new = cell(size(all)); for v=1:length(all) if any(strcmp(some,all{v})) new{v}=1; else new{v}=0; end end Alternatively, you could use intersect: [isect, index_all, index_some]=intersect(all,some); If you don't need your new values to be a cell (for zero or one, there's no reason not to use a simple array), then this is easy: new=zeros(size(all)); new(index_all)=1; If you need them to be a cell for some reason, then use: new=num2cell(new); PS: you should't use all as a variable name - it is an inbuilt Matlab function, and by overwriting it with a variable, you cannot use it until you clear the variable.

Categories : Matlab

sparse matrix parallel to the full matrix syntax of A(ind,ind)=1 in Matlab
You can use the sparse command, as follows: % create a 5x5 sparse matrix A, with 1's at A(ind,ind) [row,col] = meshgrid(ind,ind); % form indexing combinations row = row(:); % rearrange matrices to column vectors col = col(:); A = sparse(row, col, 1, 5, 5); While it is possible to index sparse matrices using the conventional A(1,2) = 1 style, generally this is not a good idea. MATLAB sparse matrices are stored very differently to full matrices behind the scenes and do not support efficient dynamic indexing of this kind. To get good performance sparse matrices should be built in one go using the sparse(i,j,x,m,n) syntax.

Categories : Matlab

find polynomial equation from array with matlab
As radarhead wrote in his comment, you forgot the coefficient of zero degree (p(4) here). Assuming x and y are vectors of same length n, polyfit(x,y,n-1) will return a vector containing the coefficients of the interpolating polynomial (of degree n-1) in descending order. Then, the value of the interpolating polynomial at a point z will be given by: p(1)*z^3 + p(2)*z^2 + p(3)*z + p(4) Don't forget p(4)! As Bas suggested, you can use the polyval function to easily compute the value of a polynomial at a a given point: polyval(p,z); To illustrate this, see the code below, which generates 4 data points, plots those points and the polynomial interpolating them: n = 4; x = sort(rand(n,1)); y = rand(n,1); p = polyfit(x,y,n-1); figure hold on plot(x,y,'bo'); xx=linspace(x(1),x(end),100);

Categories : Matlab

MATLAB curve fit display equation on graph
Probably easiest to use the fit utility which is the non-graphical equivalent of using curvefit: % sample data x=[1:10]'; y = x+randn(10,1)*0.5; plot(x,y,'o') pars=fit(x,y,'poly1'); pars contains the result of the fit, which you can overlay on the plot above with hold on plot(pars) If you want to see the values of individual parameters, you can type pars.p1 or pars.p2 (for this example, there may be other parameters "pn" for other models) To display on the figure, you can do something simple like xpos=3; ypos=9; text(xpos,ypos,{num2str([pars.p1;pars.p2])}) For more info look into the documentation for curvefit or try help curvefit or help fit.

Categories : Matlab

Syntax error in MATLAB recurrence equation
rec is not a native Symbolic Toolbox function. It belongs to MuPAD which is a separate package that Mathworks acquired and added to Symbolic Toolbox. To use it you need to first enter mupad command in command window then you enter the command that uses rec in MuPAD window that pops up.

Categories : Matlab

MATLAB - matrix multiply submatrices within a single matrix
I think you have to reshape your matrix in different way to do the vectorized multiplication, like in the code below. This code also uses loop, but I think should be faster MM = magic(2); M0 = MM; M1 = rot90(MM,1); M2 = rot90(MM,2); M3 = rot90(MM,3); MBig1 = cat(2,M0,M1,M2,M3); fprintf('Original matrix ') disp(MBig1) MBig2 = zeros(size(MBig1,2)); MBig2(1:2,:) = MBig1; for k=0:3 c1 = k *2+1; c2 = (k+1)*2+0; MBig2(:,c1:c2) = circshift(MBig2(:,c1:c2),[2*k 0]); end fprintf('Reshaped original matrix ') disp(MBig2) fprintf('Checking [ M0*M0 M0*M1 M0*M2 M0*M3 ] in direct way ') disp([ M0*M0 M0*M1 M0*M2 M0*M3 ]) fprintf('Checking [ M0*M0 M0*M1 M0*M2 M0*M3 ] in vectorized way ') disp( kron(eye(4),M0)*MBig2 ) fprintf('Checking [ M0

Categories : Matlab

MATLAB: Matrix containing values of another matrix at specific indices
You can't do it for randomly generated matrices, because you have to ensure that matrix A has lines and columns as required from the values of x and y. In this case, you can write: for i=1:length(x(:)) B(i)=A(x(i),y(i)); end B=reshape(B,size(x));

Categories : Matlab

Matlab: Finding two unknown constants/parameters in an equation
Given your two example equations; let y=x./d, then y = a+b*c y = a+a*b*c The first case is just a line, for which you can obtain a least squares fit (values for a and b) with polyfit(). In the second case, you can just say k=a*b (since these are both fitted anyway), then rewrite it as: y = a+k*c Which is exactly the same line as the first problem, except now b = k/a. In fact, b=b1/a is the solution to the second problem where b1 is the fit from the first problem. In short, to solve them both, you need one call to polyfit() and a couple of divisions. Will that work for you?

Categories : Matlab

Matlab: Improper index matrix reference (or outsmarting matlab)
In the latest versions of MATLAB (13a/13b) there's a unit testing framework built in that looks very similar to what you're attempting. Instead of expect(myfibonacci(0)).toBe(0); you would write import matlab.unittest.constraints.IsEqualTo testCase.verifyThat(myfibonacci(0), IsEqualTo(0)) (You could also/instead have assumeThat, assertThat, or fatalAssertThat). If for some reason you wish to implement your own framework, note the small difference in your syntaxes - you have a dot whereas MathWorks have a comma between myfibonacci(0) and the test condition. In MATLAB you can't index into the result of a subscripted expression like that (well, you could, but you would have to overload subsref, and that's a world of pain, trust me). So the way they've done it is to introduce the test

Categories : Matlab

Matlab solution for implicit finite difference heat equation with kinetic reactions
It looks like you are using a backward Euler implicit method of discretization of a diffusion PDE. A more accurate approach is the Crank-Nicolson method. Both methods are unconditionally stable. The introduction of a T-dependent diffusion coefficient requires special treatment, best probably in the form of linearization, as explained briefly here. It would be useful to identify stability criteria to ensure that the time and distance step lengths are appropriate following introduction of T-dependent coefficients. Note that matlab offers a PDE toolbox which might be useful to you, although I have not checked how you might use it in detail.

Categories : Arrays

MATLAB Insert matrix into 3D matrix
For horizontal or vertial concatenation of matrices/vectors A and B, you can use % vertical [A; B]; % horizontal [A, B]; % comma is optional: [A B]; There is no such notation for the third dimension. You'll have to use the generalized concatenation in arbitrary dimension cat(): % Example matrices A = rand(1437, 159, 1251); B = rand(1437, 159); % Insertion point N = 384; % How to do it A = cat(3, A(:,:,1:N), B, A(:,:,N+1:end));

Categories : Matlab

Using big matrix in Matlab
You will find an answer here on reading/writing part of a .mat matrix. %read matObj = matfile('myBigData.mat'); loadedData = matObj.X(1:4,1:4); %write matObj.X(81:100,81:100) = magic(20); EDIT Here is some code showing the append function A = ones(10,10); save('A.mat', 'A','-v7.3'); clear A matObj = matfile('A.mat','Writable',true); matObj.A(8:10,8:10) = ones(3,3) * 3; %modify matObj.A(11,:) = ones(1,10)*4; %append disp(matObj.A) The full matlab help for .mat (including limitations) is here.

Categories : Matlab

Matlab matrix with different Row Sizes
I think matrices in MATLAB have to be of a rectangular shape (m x n). You could sub in non-values for NaN as a placeholder. The way that I usually do this is define the dimensions of the matrix in nested for loops and discard elements by placing a NaN. for i = 1:rows for j = 1:5000 if timestamp != 0 yourmatrix(i, j) = timestamp; else yourmatrix(i, j) = NaN; end end end I don't completely understand all of your variables, so I can't put it directly in your function, but you can probably put it in there somewhere.

Categories : Matlab

Matlab, Matrix operation
Calling your index matrix I, try something like this: mul = A(I(:,1),I(:,2)) * A(I(:,2),I(:,3)) and see if matlab can optimize it for you. I'm rather rusty in matlab notation, so please excuse if the statement just plain out doesn't work. EDIT: I think I don't fully understand what it is you're trying to accomplish.

Categories : Performance

Matlab , matrix operations
This is one solution: % sub2ind does not work, use this hack instead z = zeros(size(A)); z(i2,i1) = 1 ind = find(z) % get linear indices %only keep the ones for which A is nonzero ind = ind(A(ind) ~= 0) Result: z = 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 0 ind = 2 4 10 12 ind = 2 4 12

Categories : Matlab

Matrix concatenation in matlab
if X is a 3x3 matrix to delete the second column do: X(:,2) = [] Then, to delete the remaining second row do: X(2,:) = [] this should do the trick. hope this helps, Scott

Categories : Matlab

Sea Ice data - MATLAB 3D matrix
Yes- this can be done without too much difficulty. I have done analogous work in analyzing atmospheric data across time. The fundamental problem is that you have data organized by hour, with grids varying dynamically over time, and you need to analyze data over time. I would recommend one of two approaches. Approach 1: Grid Resampling This involves resampling the grid data over a uniform, standardized grid. Define the grid using the Matlab ndgrid() function, then resample each point using interp2(), and concatonate into a uniform 3D matrix. You can then directly interpolate within this resampled data using interp3(). This approach involves minimal programming, with the trade-off of losing some of the original data in the resampling process. Approach 2: Dynamic Interpolation Define a

Categories : Matlab

How to exclude a set of data from matrix - Matlab
One way to create a logical matrix with true for values inside bounds is using bsxfun >> inBounds = bsxfun( @ge, A, lowerBound ) & bsxfun( @le, A, upperBound ); I used ge (greater-equal) and le (less than-equal) but you can use gt (greater than) and/or lt (less than) operators for the comparison.

Categories : Matlab

Matlab matrix image conversion
Your issue is likely arising from the fact that there are different ways of storing data (row-major vs. column-major). In this case, your .csv file clearly is not in the format you are expecting. The easiest thing to do is to simply transpose the matrix containing your data: m1 = m1'; image(m1); If there is something crazier going on and this flips it the wrong way (I don't think this should be the case, but you never know), you can try the rotate command: http://www.mathworks.com/help/matlab/ref/rot90.html

Categories : Matlab

Find index matrix Matlab
Use find and accumarray >> [r c] = find( A > 20 ); >> index = accumarray( r, c, [], @(x) {x} ) index = [ 2, 3 ] [ 2, 3 ] [] [ 1 ] Note that index is a cellarray.

Categories : Matlab

Algorithm for Matrix Inverse in MATLAB
Sigh. People think that just because they learned in school that the solution to A*X=B is to form X=inv(A)*B, that this is the thing to do. Yes, your textbook said to do that. Amazingly, there are hordes of people out there trying to teach you things like that. Sadly, they are wrong, and they teach others to teach the wrong things, even putting it into books. This foolishness propagates, never seeming to end. And even if the textbook author knows themselves that AB is better in theory than inv(A)*B, it is still easier to write it in the inverse matrix form. Alert: You don't want to form the inverse matrix, and god forbid, you don't want to use Gaussian elimination. (Let the pros do coding like that in a compiled tool for you.) Instead, use backslash in MATLAB, which IS efficient & wel

Categories : Matlab

Summing regions of a matrix that do not over lap in matlab
Since 7600 is evenly divisible by 20, you can reshape and sum: a = rand(7600,1); sum(reshape(a,20,7600/20)) EDIT Addressing comment for non evenly divisible lengths b = 20; sz = size(a); % Last elements to exclude excl = mod(sz(1),b); % Sum reshape and sum excluded separately [sum(reshape(a(1:end-excl), b, fix(sz(1)/b))), sum(a(end-excl+1:end))]

Categories : Matlab



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.