w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Concatenating numbers as string in Javascript
var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c; See jsFiddle: http://jsfiddle.net/ejDKg/

Categories : Javascript

Concatenating strings to iteration numbers in batch
@echo off SETLOCAL ENABLEDELAYEDEXPANSION set "base_name=distribution" set "dir_net_name=dir_net" FOR /L %%i IN (1,1,10) DO ( set "name=%dir_net_name%\%base_name%_%%i" echo !name! ) pause ad 1) see help for for details on /L switch. ad 2) %itnum% is redundant here. If you still need it use it as !itnum!. ad 3) %name% is evaluated before FOR loop starts, use !name! instead.

Categories : Windows

Concatenating matrix in MATLAB results in loss of precision
First, format long g worked for me. I am using Matlab_R2013a on mac: >> temp = [temp1 temp2] temp = 1334320224.86767 25.59989 -17.82167 31.19241 1334320225.03415 25.17558 -17.59459 30.71448 1334320225.20064 25.18788 -17.39987 30.61347 But a simple solution: sprintf('%f ',temp), it will lose the matrix look-like formating, but you will be able to see as you want. The output: >> sprintf('%f ',temp) ans = 1334320224.867670 1334320225.034150 1334320225.200640 25.599890 25.175580 25.187880 -17.821670 -17.594590 -17.399870 31.192410 30.714480 30.613470 If you reaaaally need to see as you pointed

Categories : Matlab

concatenating arrays in python like matlab without knowing the size of the output array
concatenate((a,b),1) or hstack((a,b)) or column_stack((a,b)) or c_[a,b] From here: http://wiki.scipy.org/NumPy_for_Matlab_Users

Categories : Python

Getting numbers based on list of other numbers in matlab / octave
you can use this function: function num = getTheMissingNumbers( from, jump, to ) num = from:to; num = setdiff( num, from:jump:to ); You can call this function >> getTheMissingNumbers( 1, 4, 16 ) to get the numbers you want. If you further assume the input to getThemissingNumbers always starts with 1, you can implement it even more efficiently using function num = getTheMissingNumbers( jump, to ) num = 1:to; num(1:jump:to) = []; % remove the elements in ind EDITED according to comment by tmpearce.

Categories : Matlab

Factor large numbers in Matlab and then get the numbers in the result
How about this : >> x=factor( sym('79228162514264337589248983040') ) x = 2^32*3*5*17*257*641*65537*6700417 >> p=char(x) p = 2^32*3*5*17*257*641*65537*6700417 >> s=regexp(p,'*','split') s = '2^32' '3' '5' '17' '257' '641' '65537' '6700417' >> exp=regexp(s{1},'^','split') exp = '2' '32' >> [exp s(2:end)] ans = '2' '32' '3' '5' '17' '257' '641' '65537' '6700417' Now play with the characters, convert them to numbers, as required.

Categories : Matlab

Read 2 numbers and skip 2 numbers in Matlab
I'm not sure what you mean by "the text file might have some other content as well". Does it mean whole lines may be discarded or that there may be non-numeric text within a line that also contains numbers? In any case if the variable line is a string of comma separated integers, you can get them into an array and extract alternate pairs of elements with sscanf, the modulus operator and logical indexing: numbers = sscanf(line, '%d,'); output = numbers(mod(0:length(numbers)-1, 4) < 2);

Categories : Matlab

Rounding numbers in matlab
By using sleight of hand. If you want to round your number x to the kth decimal place you do something like xrk = round(x*10^k)/10^k; In your instance k = 5.

Categories : Matlab

Matlab, Polygonal numbers
You can do the whole thing with the following (I think): n = 0:100; pn = (25*n.^2 - 23*n)/2; sumadetres = unique(bsxfun(@plus, pn, pn')); sumadetres = unique(bsxfun(@plus, sumadetres, pn)); The function bsxfun is really helpful in MATLAB for vectorized operations like this. You can read the documentation here. Basically bsxfun gives you an efficient way of performing element-wise binary operations between two vectors. The first expression using bsxfun in the above adds every value of pn' to every value of pn and creates a matrix of the results. By using the unique function, you only store unique values from this matrix. The second expression using bsxfun then adds every value of pn to this vector of unique results from the first expression. The result should be a vector of all unique

Categories : Matlab

How does matlab compare two complex numbers?
The complex numbers are compared first by magnitude, then by phase angle (if there is a tie for the maximum magnitude.) From help max: When X is complex, the maximum is computed using the magnitude MAX(ABS(X)). In the case of equal magnitude elements, then the phase angle MAX(ANGLE(X)) is used. NaN's are ignored when computing the maximum. When all elements in X are NaN's, then the first one is returned as the maximum.

Categories : Matlab

Matlab displaying all representable numbers
You have in fact 3 bits because there is an implied leading one: example: 1.75 = 2^0 + 2^-1 + 2^-2 So your numbers are formed of a significand with implied leading 1 + 2 bits b1 b2: 1.b1b2 = 1 + b1/2 + b2/4 multyplied by the base (2) raised to the exponent e, so finally (1 + b1/2 + b2/4) * 2^e The code used to form all the combinations is un-necessarily complex. All the possible significands could just be formed like this: significands = 1 + (0:2^p-1)/2^p; Then all the exponents: exponents = 2.^(emin:emax); Then all the numbers: floats = significands' * exponents; floats = floats(:); Instead of that, the first loop form all possible bit combinations column by column (1 combination per row, there are 2^p rows). Lets take p=3 as an example: the values of first bit are [0 0

Categories : Matlab

MATLAB Change numbers to date
For day number n use datestr(datenum(2009, 12, 31) + n, 'yyyy-mm') for example >> datestr(datenum(2009, 12, 31)+365, 'yyyy-mm') ans = 2010-12 >> datestr(datenum(2009, 12, 31)+366, 'yyyy-mm') ans = 2011-01

Categories : Matlab

Colorbar in MATLAB placing too many numbers in figure
As described in the comments, the solution is to use: set(gcf, 'renderer', 'zbuffer') As explained on http://www.mathworks.nl/matlabcentral/answers/53874

Categories : Matlab

Random numbers that add to 1 with a minimum increment: Matlab
One problem I can see is that your formula allows for numbers to be zero - when the rounding operation results in two consecutive numbers to be the same after sorting. Not sure if you consider that a problem - but I suggest you think about it (it would mean your model portfolio has fewer than N stocks in it since the contribution of one of the stocks would be zero). The other thing to note is that the probability of getting the extreme values in your distribution is half of what you want them to be: If you have uniformly distributed numbers from 0 to 1000, and you round them, the numbers that round to 0 were in the interval [0 0.5>; the ones that round to 1 came from [0.5 1.5> - twice as big. The last number (rounding to 1000) is again from a smaller interval: [999.5 1000]. Thus yo

Categories : Matlab

Matlab: how to read binary numbers from a file?
Read as strings an then convert to decimal numbers with bin2dec: bin2dec(textread('bin_MCS.txt','%s')) ans = 25166848 37749760 402653184 335544320 671088640 603979776 553649152 100664320 167773184 285213696 EDIT: To read the individual binary digits into a matrix, you can use this (48 is the ASCII code for '0'): cell2mat(textread('bin_MCS.txt','%s'))-48

Categories : File

Getting indices of most recent set of numbers in an array in Matlab?
Here is one way of doing it: I=find(diff([0, x==1, 0]),2,'last'); answer = I(1):I(2)-1; x==1 returns a logical vector that is equal to 1 everywhere x was equal to 1 and 0 otherwise. >> x==1 ans = 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 When you apply diff function on it you get another vector where the consecutive 1s are removed and the last non-zero two elements relate to the original sequence of 1s >> diff(x==1) 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 -1 0 0 0 0 0 0 However using this will fail when the first and last elements contain 1, e.g, for x=[0 0 1 1 1] or x=[1 1 1 0 0]. So we add 0 to beginning and the end and find returns their indices >> I = find(diff(x==1), 2, 'last') I = 16 21 Second argument of it says how many elements we

Categories : Matlab

I want to convert the char matrix into numbers in matlab
You can create a mapping: map = zeros(1,256); map('abc') = [1, 2, -1]; Then you can just index it with your input: x = 'abacaaaabb'; mx = map(x);

Categories : Arrays

writing float numbers to text in matlab
It's a formatting issue. If you change your fprintf line to fprintf(fid,'%1.4f ',k); you should get the same result you got in MATLAB. Check out the formatSpec section of http://www.mathworks.com/help/matlab/ref/fprintf.html

Categories : Matlab

Efficient Way to Replace Custom Strings with Numbers in MATLAB
You were on the right track. After defining: serial_numbers = {'serial1'; 'serial1'; 's2'; 'serial31010'} This seems to be simple: [~,~,new_serial_numbers ] = unique(serial_numbers,'stable') will give: new_serial_numbers = 1 1 2 3 Don't know about the performance of the 'unique' function

Categories : Matlab

Matlab: How do I remove rows that contain any of the numbers stored in a vector?
Use ismember (@Prashant's suggestion): ia = ismember(A(:,1), delindex); Or intersect: [~,ia,~] = intersect(A(:,1), delindex); To find which rows should be removed. Then remove the rows: A(ia,:) = [] Note ismember returns logical indices, while in [C,ia,ib] =intersect(A,B), ia and ib are indices. Both could be used for indexing. For more info read Matrix Indexing in MATLAB.

Categories : Matlab

Using MATLAB to find strings of numbers in nominal data
It is not obvious how this code gets your sequences of ones and zeros to start with. I am assuming that is not the hard part, so once you have that sequence, here is what I would do. if x is your sequence, first prepend and append zeros x = [0,x,0] Then take the diff to find the transitions transitions = diff(x) upTransitions = find(transitions > 0) downTransitions = find(transitions < 0) nDays = downTransitions - upTransitions + 1; You can then take a histogram hist(nDays) If you want to customize the histogram bins, just do help hist to see the options.

Categories : String

MATLAB: Given a row vector, find the indices of two nearest numbers
Try to get a distance function for each index to every other index. for i=1:length(A) for j=1:i B(i,j)=NaN; end for j=i+1:length(A) B(i,j)=abs(A(i)-A(j)); end end B = NaN 4.0000 1.0000 11.0000 2.0000 18.1000 NaN NaN 3.0000 7.0000 6.0000 22.1000 NaN NaN NaN 10.0000 3.0000 19.1000 NaN NaN NaN NaN 13.0000 29.1000 NaN NaN NaN NaN NaN 16.1000 NaN NaN NaN NaN NaN NaN [ind1,in2]=find(B==min(min(B))) ind1 = 1 ind2 = 3

Categories : Matlab

How do you format complex numbers for text output in matlab
I don't know if there is an easy way, but you can write your own format function (the hard way): function mainFunction() st = sprintfe('%d is imaginary, but %d is real!',1+3i,5); disp(st); st = sprintfe('%f + %f = %f',i,3,3+i); disp(st); end function stOut = sprintfe(st,varargin) %Converts complex numbers. for i=1:numel(varargin) places = strfind(st,'%'); currentVar = varargin{i}; if isnumeric(currentVar) && abs(imag(currentVar))> eps index = places(i); formatSpecifier = st(index:index+1); varargin{i} = fc(currentVar,formatSpecifier); st(index+1) = 's'; end end stOut = sprintf(st,varargin{:}); end function st = fc(x,formatSpecifier) st = sprintf([formatSpecifier '+

Categories : Matlab

How to get the cluster numbers for each data point when using dendrogram function MATLAB
Function dendrogram generates the dendrogram plot and (as the documentation explains) "returns T, a vector of size M that contains the leaf node number for each object in the original dataset." If you want to find all elements belonging to cluster iclust, you can try something similar to the following: iclust=2; % find all elements in cluster # 2 for example ifound = find(T==iclust); edit By the way if you want to colorize the dendrogram you can try [H, T] = dendrogram(Z,'colorthreshold',thresh); where thresh is a threshold below which branches should be colored.

Categories : Matlab

Randomly generating numbers within a fixed non-Gaussian distribution in matlab
Not quite sure what you are asking precisely, but I guess you could take a look at the random() function in the statistics toolbox: >> help random RANDOM Generate random arrays from a specified distribution. R = RANDOM(NAME,A) returns an array of random numbers chosen from the one-parameter probability distribution specified by NAME with parameter values A. R = RANDOM(NAME,A,B) or R = RANDOM(NAME,A,B,C) returns an array of random numbers chosen from a two- or three-parameter probability distribution with parameter values A, B (and C). The size of R is the common size of the input arguments. A scalar input functions as a constant matrix of the same size as the other inputs. R = RANDOM(NAME,A,M,N,...) or R = RANDOM(NAME,A,[M,N,...]) returns an M-by-N-by-...

Categories : Matlab

Given 4 numbers of array of 1 to 10 elements. Find 3 numbers whose sum can generate all the four numbers?
Since the solution contains only 3 numbers which are in 1..10 range, brute force is an effective algorithm here (at most 1000 possibilities to check even in naive implementation). So C# code could be public static int[] BruteForce(int[] data) { HashSet<int> hs = new HashSet<int>(); for (int x = 1; x <= 10; ++x) for (int y = x; y <= 10; ++y) for (int z = y; z <= 10; ++z) { hs.Clear(); for (int i = 0; i < data.Length; ++i) hs.Add(data[i]); hs.Remove(x); hs.Remove(y); hs.Remove(z); hs.Remove(x + y); hs.Remove(x + z); hs.Remove(y + z); hs.Remove(x + y + z); if (hs.Count <= 0) return new int[] { x, y, z }; // <- Solution } return new in

Categories : Arrays

Java arraylist. I need to pass random numbers to an array list and pass them to another class to check those numbers against another set of numbers
You can always transform the random int to a string by using Integer.toString() before inserting into your array list. You can convert the String back to int using Integer.parseInt() E.g. for (int i = 0 ; i < 3 ; i++) { locations.add(Integer.toString((int)(Math.random() * 5)); }

Categories : Java

Concatenating two string (K&R)
Two problems: No space for terminating null character in outword. Needs to be: char outword[strlen(lword) + strlen(rword) + 1]; /*^^^*/ This is undefined behaviour as i is being modified twice in the same statement: outstr[i++] = lstr[i++]; /* Change to: */ while (lstr[i] != '') { outstr[i] = lstr[i]; ++i; } With these two changes the program produces a new concatenated string (http://ideone.com/9QbU0q).

Categories : C

concatenating strings in .each loop
You can use an array for that. Like this... jQuery('#updateAllContentButton').click(function() { var count = 1; var arr = []; jQuery('.CommentaryItem').each(function() { var id = GetID(jQuery(this)); var data_str = (id + ':' + count + '~'); arr.push(data_str); //console.log(data_str); count++; }); console.log(arr.join()); });

Categories : Javascript

Error while concatenating the string
The problem is that you try to reallocate memory that is not allocated (in the way realloc wants it) in the first place. You declare str1 as an array in the main function, this memory will be allocated on the stack by the compiler and not on the heap. The realloc function only can reallocate memory allocated on the heap, either by malloc, calloc or an earlier realloc call. And if the realloc call would have worked, then you have a memory leak, as you allocate memory and assign it to newstr1 and in the next line overwrite the newstr1 pointer with the newstr pointer. And you should really not allocate a fixed size, remember that you append one string of size m to a string of size n. Think about what would happen if m + n is larger than 9. Which leads to the next problem, that you don't te

Categories : C

Concatenating and Pattern Matching SQL
Are you after something like this: SELECT `c`.`user_id`, `c`.`zip`, `a`.`city`, CONCAT_WS( ';', `c`.`city`, `aa`.`city-state` ) AS `location` FROM `Accounts` AS `a` LEFT JOIN `Addr` AS `aa` ON `aa`.`zip`, `a`.`id` LEFT JOIN `Customer` AS `c` ON `c`.`user id`, `a`.`id`

Categories : SQL

Concatenating Columns Pandas
You could do In [278]: df = pd.DataFrame([[1, np.nan], [2, np.nan], [np.nan, 3]]) In [279]: df Out[279]: 0 1 0 1 NaN 1 2 NaN 2 NaN 3 In [280]: df.sum(1) Out[280]: 0 1 1 2 2 3 dtype: float64 Since NaNs are treated as 0 when summed, they don't show up. A couple of caveats: You need to be sure that only one of the columns has a non-Nan for this to work. It will also only work on numeric data. You can also use df.fillna(method='ffill', axis=1).iloc[:, -1] The last column will now contain all the valid observations since the valid ones have been filled ahead. See the documentation here. The second way should be more flexible but slower. I slice off every row and the last column with iloc[:, -1].

Categories : Python

Ruby concatenating best practice
First: I would actually say that the most "Ruby" way of handling this—avoiding the nil issue, that is—would be to use string interpolation: "#{first} #{mi} #{last}" This works just fine in case any of the above variables is nil, because it will simply result in blank space in the string. As for the conditional space issue: There are plenty of ways to skin that cat. I really like sawa's idea. Here's another, which I've seen variants of, though it's not particularly efficient (but 9 times out of 10 that doesn't matter): [first, mi, last].compact.join(" ") Lastly: for the "plus comma + suffix if present" requirement, that's complicated enough that I'd recommend writing a little method to separate that logic out: def suffix_if_necessary(name) suffix ? "#{name}, #{suffix}" : name

Categories : Ruby

Concatenating Values Within SQL XML field
I've thought of a hack to achieve this... SELECT REPLACE( REPLACE( REPLACE( CAST([myField] As NVARCHAR(MAX)), '<values><value>', ''), '</value></values>', ''), '</value><value>', ';' ) As [Hacked] FROM [myTable] ...but it makes me feel a bit dirty. There has to be a better way.

Categories : SQL

PDO concatenating SQL Query with placeholders
If I understand you correctly, attempting to bind parameters that don't exist is causing your query to fail. Based on that, you should just add a check for those properties: public function topCarrier() { $Q = $this->buildQ(); $query = $this->_INSTANCE->pdo->prepare($Q); if($this->start_date!=0 and $this->end_date!=0) { $query->bindValue(":start_date",$this->start_date); $query->bindValue(":end_date",$this->end_date); } $query->execute(); while($data = $query->fetch()) { $this->data[$data['shipped_by']] = $data['total']; } return $this->data; }

Categories : PHP

Concatenating my object with a string
The ideam is to create a class MyTypeNameList when using the macro like this Listof(MyTypeName) It is a shortcut to create class named XXXXList declared with a default CTOR, and a member itsLength; example in your code : //declare a class Listof(A) after preprocessor this is class AList{ public: AList(){} private: int itsLength; };

Categories : C++

sql - concatenating case statements
I don't think you can make your query shorter. You even use separate fields. Technically you could use some functions that do the CASE WHEN work, but I don't think the gain is enough. CREATE FUNCTION CheckAndAdd(@str VARCHAR(255)) RETURNS VARCHAR(255) AS BEGIN RETURN CASE WHEN @str <> 'EMPTY' AND @str <> '' THEN '-['+@str+']' ELSE '' END END Note that if a CASE fails and it doesn't have an ELSE it returns NULL, and in SQL 'Hello' + NULL = NULL Simple test: SELECT 'Hello ' + CASE WHEN 1 = 0 THEN 'None' END + ' World' Correct test: SELECT 'Hello ' + CASE WHEN 1 = 0 THEN 'None' ELSE '' END + ' World'

Categories : SQL

Concatenating binding data
In a Binding, the StringFormat property only works on properties of type String. As MSDN states: A string that specifies how to format the binding if it displays the bound value as a string. The easiest way to solve your problem is to write an IValueConverter. This converter will take your input value and return a SolidColorBrush. For instance, if your hex values are strings, the converter's Convert method: public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var str = (string)value; var r = Byte.Parse(str.Substring(0, 2), NumberStyles.HexNumber); var g = Byte.Parse(str.Substring(2, 2), NumberStyles.HexNumber); var b = Byte.Parse(str.Substring(4, 2), NumberStyles.HexNumber); return new SolidColorBrush(Color.FromRgb(r,

Categories : C#

python list duplicating instead of concatenating
You are not using the class attributes, but the global variables you have defined by chance. return str(user) + " " + str(item) + " " + str(rating) Should look like return str(self.user) + " " + str(self.item) + " " + str(self.rating)

Categories : Python

Add new line while concatenating variable string
Try using <br> var arrBackImg = new Array(); var frontText = new Array(); for(......) { frontText[i] = title+"<br>"+description; backText[i]=title+":"+longdesc; } <br> is the tag used for line breaks in HTML

Categories : Jquery



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