w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to find the mapping after permutation of a 2-d matrix in Matlab
low hanging fruits first. Suppose there are no duplicate rows: % compute the permutation matrix P = all( bsxfun( @eq, permute( A, [1 3 2]),permute(B,[3 1 2]) ), 3 ); [~, p] = max(P, [], 2 ); % gives you what you want If there are duplicates, we need to "break ties" in the rows/columns of P: n = size(A,1); bt = abs( bsxfun(@minus, 1:n, (1:n)' ) )/n; %//' [~, p] = max( P+bt, [], 2 );

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

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

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

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: 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 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

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

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

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

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

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

Get rid of identical permutations in a matrix, Matlab
this is not much better than transform the numbers into number sequences. but it is the same idea, i.e. mapping groups of numbers to a unique identifier. Here is my code. M=[1 2 3 4 5 6 7 8 9 10;1 2 3 4 8 9 10 5 6 7;5 6 7 8 9 10 11 1 2 3;5 6 7 8 1 2 3 9 10 11]; %chop matrix into mental columns M4=M(:,1:4); M3=[M(:,5:7);M(:,8:10)]; % stack the 3s together [u_M4,ia_M4,ic_M4]=unique(M4,'rows');% give each unique row of 4 a one digit id [u_M3,ia_M3,ic_M3]=unique(M3,'rows');% give each unique row of 3 a one digit id idx3=[ic_M3(1:length(ic_M3)/2) ic_M3(length(ic_M3)/2+1:end)]; % reshape the ids for the 3 so it matches the original format sort_idx3=sort(idx3,2); % sort idx=[ic_M4 sort_idx3]; % construct the idx matrix consist of the one digit ids [u_idx,ia_idx,ic_idx]=unique(idx,'rows'); %fi

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

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

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 simple matrix manipulation
If dimension are correct you can always use * operator >> C = B*A C = 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16

Categories : Matlab

Matlab matrix Vs Python arange
arange's stop (the second argument) is excluded in output. >>> arange(0, 10, 2) array([0, 2, 4, 6, 8]) >>> len(_) 5 According to arange docstring: arange([start,] stop[, step,], dtype=None) ... Values are generated within the half-open interval [start, stop) To get same result with matlab, adjust stop (the second argument): arange(dt, (a*T)+dt, dt)

Categories : Python

MATLAB Inner matrix dimensions must agree
Your missing the dot before /: y=((exp(t/10).*sin(t)) ./ ((t.^2)+1)) Note: You can easily find problems like this on your own. You could have done ((exp(t/10).*sin(t)) and seen that it works as expected. Then you could try ((t.^2)+1)). Wow, that works as well. Thus, the problem has to be cause by the /. From there to ./ it is just a small step.

Categories : Matlab

Matlab column multiplication of a matrix
You can simply use the inbuilt prod function as prod(A,2) or prod(A')'. For example: >> A = [ 1 1 4 3 2 2 2 1 1 4 1 1 ]; Now: >> prod(A,2) ans = 4 12 2 4 For more details, try help prod.

Categories : Matlab

Read CSV file in Matlab to matrix
I'll offer this up, but it's not much % read in the entire file fid = fopen('tmp.csv'); A = fread(fid); % convert to a character array B = char(A)'; % create a cell array with one element for every line in the file lineData = regexp(B,' ','split'); % for every line in the data, parse out all the data into a % cell array data = cell(1,length(lineData)); for ii=1:length(lineData) pData = textscan(lineData{ii},'%s','Delimiter',','); % remove any spaces from the elements data{ii} = cellfun(@(x) strrep(x,' ',''), pData{1},'UniformOutput',false); end

Categories : Matlab

Getting one section of a larger matrix matlab
As schorsch said in comments, simply do: A=M(160:430,108:305) to get values then modify your sample ( B=transform(A) ) and put B in the same way you got A out M(160:430,108:305)=B Remember that : basically means everything in between I agree with Mark though, the documentation for MATLAB is outstanding and one of MATLAB's best features compared to open source, utilize it please.

Categories : Matlab

what is the algorithm for an RBF kernel matrix in Matlab?
This should be what you are looking for. It is taken from here % With Fast Computation of the RBF kernel matrix % To speed up the computation, we exploit a decomposition of the Euclidean distance (norm) % % Inputs: % ker: 'lin','poly','rbf','sam' % X: data matrix with training samples in rows and features in columns % X2: data matrix with test samples in rows and features in columns % sigma: width of the RBF kernel % b: bias in the linear and polinomial kernel % d: degree in the polynomial kernel % % Output: % K: kernel matrix % % Gustavo Camps-Valls % 2006(c) % Jordi (jordi@uv.es), 2007 % 2007-11: if/then -> switch, and fixed RBF kernel function K = kernelmatrix(ker,X,X2,sigma) switch ker case 'lin' if exist(

Categories : Algorithm

Multiplying matrix polynomials in MATLAB
It's probably not the best solution, but you could reimplement conv for matrices, e.g.: function C = convMat(A,B) nA = size(A,3); nB = size(B,3); n = nA + nB - 1; C = zeros([size(A,1),size(B,2),n]); for k = 1:n for j = max(1,k+1-nB):min(k,nA) C(:,:,k) = C(:,:,k) + A(:,:,j)*B(:,:,k-j+1); end end For your interest: Another (worse?) implementation: function C = convMat2(A,B) n = size(A,3) + size(B,3) - 1; C = zeros([size(A,1),size(B,2),n]); for mA = 1:size(A,1) for mB = 1:size(B,2) for l = 1:size(A,2) % = size(B,1) vA = A(mA,l,:); vA = vA(:); vB = B(l,mB,:); vB = vB(:); C(mA,mB,:) = C(mA,mB,:) + reshape(conv(vA,vB),[1,1,n]);

Categories : Matlab

extract the matrix from strel matlab
Use the STREL object's getnhood() function: SE.getnhood() ans = 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0

Categories : Matlab

Matlab: column of empty matrix
This is kinda clumsy, but it works and is shorter than an if or try: A(:,1:min(1,size(A,2))) or A(:,1:9999999999:size(A,2))

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

matlab matrix operation speed
EDIT: I improved the tests to give more accurate times. I also optimized the unrolled version which is now much better than what I initially had, still matrix multiplication is way faster as you increase the size. EDIT2: To make sure that the JIT compiler is working on the unrolled functions, I modified the code to write the generated functions as M-files. Also the comparison can now be seen as fair as both methods get evaluated by passing TIMEIT the function handle: timeit(@myfunc) I am not convinced that your approach is faster than matrix multiplication for reasonable sizes. So lets compare the two methods. I am using the Symbolic Math Toolbox to help me get the "unrolled" form of the equation of x'*A*x (try multiplying by hand a 20x20 matrix and a 20x1 vector!): function f = buil

Categories : Performance

Matlab Bug -- Matrix Elements Keep Maxing Out
It's not a bug - it sounds like you are using a uint8 datatype. If you convert to a datatype with more bits - e.g. uint16, uint32, single, double, etc - you will not run into this problem. I guess you are working with images, as images read using imread are read in as uint8 by default to save memory. Quickest fix: use I=double(I); either at the start of your function, or on the variable I before you put it into the functions.

Categories : Matlab

Creating dataset from matrix in Matlab
Have you considered using a struct? I use these all the time in MATLAB for database things, I know it works absolutely fantastic for up to 20,000 elements with about 15 fields each, so I think it would still work just as well as anything else for 2 million items with 2 fields. Alternatively, can't you just put it in a cell array? DataBase{rowNum,1}=dataVector(rowNum,:); DataBase{rowNum,2}=label{rowNum}; To preallocate a struct or cell, its relatively easy, with a struct, once you make your first one to initialize the fields, just say Struct(2000000).fieldName =[] TO preallocate your cell array, just do DataBase={[]} DataBase{2000000,2}=[] This preallocates all of it and fills it with empty values.

Categories : Matlab

Matlab: accessing a matrix like a database
The exact answer to your question is to use ismember: octave> years = [2010 2011]; octave> ismember (M(:,1), years) ans = 1 1 1 0 octave> M(ismember (M(:,1), years), 2) ans = 5 7 8 However, depending what you gonna be doing with the data, it may be better to rearrange it in some other way. For example, maybe a cell array, one cell for each year holding an array with the values. octave> M([2010 2011 2012]) = {[5 7] [8] [20]}; octave> M{2010} ans = 5 7 Or if you gonna have more numbers for each entry, maybe a struct array with each struct having multiple fields, one of them the year. I have written before a recipe to deal with such data before. But really, if your data gets complicated and you think need a database, then this is probabl

Categories : Matlab

How to loop a matrix with a window in Matlab
use blockproc if you have the image processing toolbox. Another option is using im2col with the 'distinct' block type: B = mean(im2col(A,[m n],'distinct'));

Categories : Matlab

MatLab to convert a matrix with respect to 1st col
I think options 1 is better, i.e. first make r, and then remove 99999. Having r, u can remove 99999 as follows: r2 = {}; % new cell array without 99999 for i = 1:numel(r) rCell = r{i}; whereIs9999 = rCell == 99999; rCell(whereIs9999) = []; % remove 99999 r2{i} = rCell; end Or more fancy way: r2= cellfun(@(c) {c(c~=99999)}, r);

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

Efficient way of converting matlab matrix to array in c++
If the value is constant (as in, you are happy to recompile for each time you want to change the values), then you can do: double f[] = { -.000212080863, .000358589677, .002178236305, ... }; (Note the addition of commas, and curly brackets instead of square ones). If the values are changing, then you want to use a vector<double> f;, clean up the input a bit and use something like: ifstream infile("numbers.txt"); while(infile >> value) { f.push_back(value); }

Categories : C++

how to get the length (count of rows) of this matlab matrix?
Just use the size function size(ans, 1) But if you're asking this, I suggest you work through some basic Matlab tutorials before you continue...

Categories : Matlab

Combine matrix column in one vector Matlab
It looks to me that A is a cell array, not a matrix. In which case you can do the following: B = [A{:}]; or, since the individual elements in A are column vectors in your example, At = cellfun(@transpose, A, 'uniformoutput', false); B = [At{:}]; Or just B = vertcat(A{:}); (Thanks @horchler for reminding me of the simple...)

Categories : Matlab

How do i add a random number to each matrix element in matlab?
you can add the random to X instead of m rX = X + rand(size(X)); % add uniformly distributed random numbers in [0,1] interval m=[rX(:,1) H(:) rX(:,2) H(:) rX(:,3) H(:)];

Categories : Matlab



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