I would like to verify whether an element is present in a MATLAB matrix.

At the beginning, I implemented as follows:

```
if ~isempty(find(matrix(:) == element))
```

which is obviously slow. Thus, I changed to:

```
if sum(matrix(:) == element) ~= 0
```

but this is again slow: I am calling a lot of times the function that contains this instruction, and I lose 14 seconds each time!

Is there a way of further optimize this instruction?

Thanks.

Answer:

If you just need to know if a value exists in a matrix, using the second argument of find to specify that you just want one value will be slightly faster (25-50%) and even a bit faster than using `sum`

, at least on my machine. An example:

```
matrix = randi(100,1e4,1e4);
element = 50;
~isempty(find(matrix(:)==element,1))
```

However, in recent versions of Matlab (I'm using R2014b), `nnz`

is finally faster for this operation, so:

```
matrix = randi(100,1e4,1e4);
element = 50;
nnz(matrix==element)~=0
```

On my machine this is about 2.8 times faster than any other approach (including using `any`

, strangely) for the example provided. To my mind, this solution also has the benefit of being the most readable.

mysql,performance,explain

I'm creating a DB from scratch and I'm trying to create queries with performance in mind. For test purpose I filled my tables with test data. My query needs to join 3 tables: 2 with millions of rows and the third with hundred thousands rows. How can I know my...

javascript,jquery,arrays,performance,underscore.js

I am looking to create a function in javascript, which would allow me to pass a long array, together with one argument. what I'm looking for is something like this: var ar = [1,2,3,4]; var pairs = superAwesomeFunction(ar,2) //=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]; var trebles = superAwesomeFunction(ar,3) //=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4] ideally, the function would...

image,matlab,image-processing,mask,boundary

I'm trying to create a mask (or similar result) in order to erase pieces of a binary image that are not attached to the object surrounded by the boundary. I saw this thread (http://www.mathworks.com/matlabcentral/answers/120579-converting-boundary-to-mask) to do this from bwboundaries, but I'm having trouble making suitable changes to it. My goal...

matlab,simulink

I am working on a simple System Object in Matlab/Simulink. It looks like this : classdef realtime_header_detectorSO < matlab.System & matlab.system.mixin.Propagates % correlateHeader % % This template includes the minimum set of functions required % to define a System object with discrete state. properties Header %nrOfBitsInPreviousStep=0; s=100; d=zeros(1,s); end properties...

matlab,typeconverter

I'm currently using a MATLAB to work and I need some help: I need to convert my output data (variable: units) be a double instead of a cell because I must perform a sum: units = inputdlg(question,title); sum = units + i; I've tried this code also but didn't solve...

matlab,machine-learning

This is my implementation of CostFunctionJ: function J = CostFunctionJ(X,y,theta) m = size(X,1); predictions = X*theta; sqrErrors =(predictions - y).^2; J = 1/(2*m)* sum(sqrErrors); But when I try to enter the command in MATLAB as: >> X = [1 1; 1 2; 1 3]; >> y = [1; 2; 3];...

matlab

Is it possible to add statements in between the codes. For example: If I have a code like this, r(:,1) = a(:,1) - a(:,2); Then can I write it as, r(:,1) = a(:,1)("this is a constant") - a(:,2)("this is a variable"); ...

matlab,time-frequency

Code tfr = abs ( tfr ); [row_size, column_size] = size(tfr); tfr = tfr(1:round(row_size/2), 1:row_size); surf(tfr); view(2); I get in R2014b of OSX 10.10.3 Yosemite but rotating around shows that the cells should not be black Why is the output black? I wonder if this is a hardware problem or...

matlab,system,equation

sorry if it already has a answer..i tried other links but it didn't understand i have 2 1*63 array .landa and v. each of their members are syms. and each v member is a function of all landa members.i have already calculated v members and they are all symbolic equations...

matlab,image-processing

I have a binary matrix containing several binary objects and I want to bridge between them. Actually I have the following picture: And the result has to be like this: Is there any function or a shortcut way, other than loops, for this problem?...

matlab,filtering,convolution

I'm trying to design a Wiener filter in Matlab for a deconvolution problem but I'm having a lot of problems. I have a gaussian white noise process with a variance of 1.2 and a impulse response which has length two. Its values are g(0) = 5 and g(1) = 4....

matlab,distribution,sampling,random-sample

How can I create a vector x in Matlab that has values between 0.8 and 1.2, randomly sampled from a: 1. Uniform 2. Normal distribution? There are a lot of functions dealing with distributions, but I'm having trouble using them properly....

matlab

What is the ellipsis for in this Matlab statement? frame = insertObjectAnnotation(frame, 'rectangle', ... bboxes, labels); ...I could not find in their online doc....

matlab,plot,signals,circle

I have some random signal (for example sin signal) with the time scale. t=0:0.1:2*pi y=sin(t) plot(t,y) Now I want to draw this signal on this circle. So the time vector actually becomes an envelope of the circle. Envelope of the circle represents "y = 0" in cartesian coordinate system. Here...

matlab,events,delay

In Matlab functions can be started at events,but occasionally, like with the resize function, the events are called in rapid order and the function is called many times in succession, which can cause weird behavior and lag. Is there a way to have it listen for the event but only...

matlab,image-processing

I am trying to read all the images in the folder in MATLAB using this code flst=dir(str_Expfold); But it shows me output like this. which is not the sequence as i want. Can anyone please tell me how can i read all of them in sequence? for giving downmark, please...

matlab,plot

I want to display three figures in a figure window. Assuming that I divide 2x2 regions. subplot(2,2,1) ---------+----------- | R1 | R2 | ---------+----------- | R3 | R4 | ---------+----------- I want to show a figure merging R1 and R3 ant other two in R2 and R4 I can display...

java,mysql,sql,performance

I have a table as follows: CREATE TABLE IF NOT EXISTS mytable ( `id` INT(22) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `uuid` VARCHAR(255) NOT NULL, `x` INT(11) NOT NULL, `y` INT(11) NOT NULL, `z` INT(11) NOT NULL, `time` BIGINT NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY idx_table_x_y_z ( x,...

java,performance,jpa,openjpa

I have a rest web app with cxf 3.0.1 framework and openjpa 2.3.0. The web.xml: <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Mobile app rest services</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/cxf-servlet.xml</param-value>...

matlab

So, I want to be able to look at (read: copy) MATLAB's NonLinearModel method of printing the regression results to the screen such as this. Nonlinear regression model: y ~ (alpha1 - alpha2*t^0.5) Estimated Coefficients: Estimate SE tStat pValue alpha1 1.0253 0.0082253 124.66 4.8823e-24 alpha2 0.0061783 0.00073277 8.4314 4.4834e-07 Number...

string,matlab,filenames

I am using the below mentioned code to get the file names of images according to their id's from images_1 text file as strings and use them to read the images from their directory image_count=1; for image_count=1:6 file=fopen('D:\Academics\New folder\CUB_200_2011\images_1.txt','r'); C = textscan(file, '%s'); original_image=imread('D:\Academics\New folder\CUB_200_2011\images\%s','C{1}{2*(image_count)}'); imshow(original_image) end I am able...

matlab,matrix

I have a matrix looks like: 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 0 4 0 0 0 0 0 3 0 0 6 0 0 4...

arrays,matlab

I have two vectors, one of them stores the width dimension of a set of images and another one the height of these set of images. I want to use these values as two dimensional vectors [width height] and store them in a matrix. The first line, for instance, keeps...

javascript,performance

How do I get the number of zero decimals behind the comma (but not the total)? So to illustrate an example: 0.00001 > 4 0.000015 > 4 0.0000105 > 4 0.001 > 2 I am looking for methods that are efficient (meaning that they optimize the calculation time)....

matlab,matlab-figure

I'm struggling to plot multiple functions on one figure. Here is the code that I have: syms t a; a=0.9514; F1=0.5*sqrt(3*t^2); F2=-0.28375*t^2+1.155*a*(t-a)+1; F3=1; E1=diff(F1,t); E2=diff(F2,t); E3=diff(F3,t); I want to plot E1, E2 and E3, each only within a certain range, to make a "composite" line. I've tried plotting with ezplot...

matlab,polynomial-math

I have the following code: syms z Gc=1.582*(1-0.3679*z^-1)/(1+.418*z^-1); Ghp=.3679*(z^-1)*(1+.718*z^-1)/((1-z^-1)*(1-.3679*z^-1)); T=(Gc*Ghp)/(1+Gc*Ghp); clipboard('copy', latex(simplifyFraction(T))); Which results in following for T: How can I normalise coefficients? I.e. I want the z2 in denominator and z in numerator to have the coefficient of 1. Is there any function in Matlab to do so?...

performance,go,hashmap

I have this snippet of code that iterate over a map and filter some fields based on relation type, I have to run two loops and have a feeling that it is going to be slow for big maps. Is there any way I can technique/refactoring to make this code...

android,performance,sqlite,compare

We are developing an Android App based on a product that already has a website. As a result, when launching the Android app it may happen that a lot of things differ between the local SQLite database and our central database. What is the fastest way to synchronize the Android...

matlab

I have 20 column vectors in the workspace and I'd like them all to be contained within a cell array. They're all labelled data1, data2, data3,...data20. Is there a faster way to do this than: cell = {data1, data2, data3, data4, data5, data6, ...} all the way up to data20?...

sql-server,performance,timestamp

I have a simple SQL query to count the number of telemetry records by clients within the last 24 hours. With an index on TimeStamp, the following query runs in less than 1 seconds for about 10k rows select MachineName,count(Message) from Telemetry where TimeStamp between DATEADD(HOUR,-24, getutcdate()) and getutcdate() group...

performance,mongodb,indexing

Say I have a collection containing documents like the one below: { _id: ObjectId(), myValue: 123, otherValue: 456 } I then create like below: {myValue: 1, otherValue: 1} If I execute the following query: db.myCollection.find({myValue: 123}) will I get the same performance with my index as I would if I...

image,matlab,image-processing,computer-vision

I need to save a set of pre-processing images in matlab, resulting in grayscale images. The problem is the fact that these pre-processed images have pixel values higher than 255. If I save them with imwrite() as, for instance, .PNG files, does matlab normalize the values to be in [0,255]...

matlab,plot

I have multiple 2D line plots in Matlab (they represent some wave moving through space). Each plot represents the wave at some time t. I want to animate through these plots (i.e. show the first plot for a fraction of a second, then show the next one, and the next,...

matlab,matrix,least-squares

How can I solve , where and and in the least squares sense in matlab? So I'd like to have the minimizing as output....

matlab,plot,legend,movie

i have a question regarding legend for movies. This is my code: fig = figure(); for i = 1: 70000 plot(signal1) hold on; plot([i,i],[-5,5]) plot(signal2,'r') hold off; title('\fontsize{14} my data'); legend('signal1','signal2'); axis tight; f(i) = getframe(fig); end The legend shows the same colors for the first two things I plot....

javascript,performance,reactjs,reactjs-flux,flux

I am new on React and Flux and I am making an app that will have an input (like the name or the title), and below a list of n things. How should I handle the event listeners? I saw in the TODO example of flux (https://github.com/facebook/flux/blob/master/examples/flux-todomvc/) that they use...

string,matlab

I have a string "FDFACCFFFBDCGGHBBCFGE" . Could anyone help me to generate a new string with the same order but no element inside repeated twice. Thanks ! The expected output should be like this : "FDACBGHE"...

matlab,svm,auc

I'm having a weird problem in training an SVM with an RBF kernel in Matlab. The issue is that, when doing a grid search, using 10-fold cross-validation, for the C and Sigma values I always get AUC values equal to approximately .50 (varying between .48 and .54 depending) -- I...

c#,multithreading,performance,loops

I'm having some performance issues when starting my windows service, the first round my lstSps is long (about 130 stored procedures). Is there anyway to speed this up (except for speeding the stored procedures up)? When the foreach is over and goes over to the second round it goes faster,...

java,performance,object

I have this loop which runs about 1,000,000 times. while ((line = br.readLine()) != null) { if(!(line.isEmpty())){ data = new JSONObject(line); name = (String)data.get("name"); surname = (String)data.get("surname"); ar.put(name, surname); //an array } } What are the advantages (if any) in terms of efficiency of having it like that were data,name...

c++,matlab

Is there an alternative way to call a C++ class using MATLAB, and operate its methods on MATLAB variables?

matlab

my matlab version is 2012a. when I use fitcknn,has this error: Undefined function 'fitcknn' for input arguments of type 'cell'. how to calculate probability for each class for predicate with knn without fitcknn? after use this code, I want to calculate prob_estimates for each neighbors: knn = ClassificationKNN.fit(trainsample, trainlabel,'NumNeighbors',7); y...

image,matlab,image-processing,image-segmentation

I have an image which I want to divide into overlapping blocks. I have set the box to be of size 8 rows and 8 columns, and the overlapping factor to be 4 rows/columns. This is what I have written to solve this: img = imread('a03-017-05.png'); overlap = 4 count...

matlab,matrix,multidimensional-array,scalar

I'm having problems multiplying specific values within my multidimensional matrix by a scalar. My matrix has the following dimension: size(comDatabe) = 5 10 3 397 10 The third dimension is an x-y-z coordinate frame. Something went wrong and now my y-axis is defined upside down for one subject (#8 out...

python,performance,loops,cmd,progress

I have a small Python script which sends POST requests to a server and gets their response. It iterates 10000 times, and I managed to print the current progress in command prompt using: code=current_requestnumber print('{0}/{1}'.format(str(code),"10000"),end="\r") at the end of each loop. Because this involves interaction with a webserver, I would...

javascript,angularjs,performance,caching,angularjs-ng-repeat

We have huge rendering spikes with ng-repeat in Angular application. Main page shows a huge list of cover images ("::" and "track by" are in place). On first load it works acceptable. But if user changes the state (we use UI-Router) and goes back to the home page afterwards then...

android,performance,opengl-es,opengl-es-2.0

So Im trying to figure out how to draw a single textured quad many times. My issue is that since these are create and deleted and every one of them has a unique position and rotation. Im not sure a vbo is the best solution as I've heard modifying buffers...

matlab,loops,for-loop,while-loop,do-while

This is my one dimensional array A. containing 10 numbers A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

matlab,image-processing

I have a labeled matrix containing two objects. How can I thicken an object to a curve? Actually I have the following image: and I want this: Each pixel of the resulting curve is the median of each column. But if you have another idea, it is acceptable, because I...

matlab,plot

I have a semilogarithmic plot which works so far with semilogx. Now I would like to change the tick labels. Now it says 10^8 10^9 ... 10^13, but I would like to see 1e8, 1e9, ... 1e13 on the x-axis. How can I change that? Cheers Manuel...