I think it's a simple question. I want:
a = 1.154648126486416;
to become:
a = 1.154;
and not:
a = 1.15000000000;
How do I do that without using format('bank').
You could do this:
a = floor(a*1000)/1000;
Building on #gnovice's answer, you can format the output as a string to get rid of the extra zeros. See the sprintf documentation for all the formatting options.
str=sprintf('The result is %1.3f.',a);
disp(str)
will show "The result is 1.154." in the command prompt. Or write the string to file, etc., etc.
a = 1.154648126486416;
% desired precision
b = -3;
% your answer
ans = floor(a*10^(-b))/(10^(-b));
The answer is 1.1540
this is good if you don't care about the rest of digits but if you do care then you just have to simply change "floor" to "round".
ans = round(a*10^(-b))/(10^(-b));
The answer is 1.1550
Related
The problem I have is that it only works partially, but what can I add to make it work?
A2 = [20 4 6 8 5];
A3 = [10 2 3 4 6];
Str=[];
formatSpec = 'P%d (%d,%d)';
for i=1:length(A2)
str = char(sprintf (formatSpec, i, A2(i),A3(i)));
Str=[Str;str];
end
set(handles.text2,'string',Str);
You are not concatenating strings but char-arrays. Thinking it this way, it already answers your question: If you have a two-digit number, the char-array is one element longer than the char-array of a single-digit number... and you cannot concatenate two arrays of different size vertically.
The solution is fairly simple: use actual strings (introduced somewhere around R2016a). Strings are indicated with "" instead of '', which are chars. So replace your charwith string and it works fine. (Even better: provide the formatSpecas ""-string and it sprintf() will return a string right away)
Side note:
BTW, you should always allocate memory if your are looping. That is why the Str has an orange squiggly underline. This is because MATLAB stores arrays in RAM contiguously and has to copy it to a larger section it it outgrows the current one.
So instead of Str=[], write Str = strings(length(A2),1), and index Str(i) = ... in the loop.
Personally, I like num2str more that sprintf but I cannot give a good reason for this, except for that it also works without providing a format.
I have a question on the following line on a MATLAB script. What does '%2.2g' mean in this line? I know it is use to format a number notation. Are there other options as to changing it to a 10^1, 10^2, 10^3? Can anyone find some resources for me to read?
num2str((rng'* (sp(t)-sa(t))) + sa(t),'%2.2g')
%a.bg :
a: stands for the width of the number
b: the number of decimals printed.
g: chooses the more compact of %e or %f. (Insignificant zeroes do not print.)
For example:
>> sprintf('%2.2g', 1.23)
ans =
1.2
>> sprintf('%2.2g', 123000)
ans =
1.2e+05
Note that it rounds the result.
For exponential notation just use something %2.2e.
For formatting rules just look at the documentation: Formatting Text- Matlab
I want to use fscanf for reading a text file containing 4 rows with an unknown number of columns. The newline is represented by two consecutive spaces.
It was suggested that I pass : as the sizeA parameter but it doesn't work.
How can I read in my data?
update: The file format is
String1 String2 String3
10 20 30
a b c
1 2 3
I have to fill 4 arrays, one for each row.
See if this will work for your application.
fid1=fopen('test.txt');
i=1;
check=0;
while check~=1
str=fscanf(fid1,'%s',1);
if strcmp(str,'')~=1;
string(i)={str};
end
i=i+1;
check=strcmp(str,'');
end
fclose(fid1);
X=reshape(string,[],4);
ar1=X(:,1)
ar2=X(:,2)
ar3=X(:,3)
ar4=X(:,4)
Once you have 'ar1','ar2','ar3','ar4' you can parse them however you want.
I have found a solution, i don't know if it is the only one but it works fine:
A=fscanf(fid,'%[^\n] *\n')
B=sscanf(A,'%c ')
Z=fscanf(fid,'%[^\n] *\n')
C=sscanf(Z,'%d')
....
You could use
rawText = getl(fid);
lines = regexp(thisLine,' ','split);
tokens = {};
for ix = 1:numel(lines)
tokens{end+1} = regexp(lines{ix},' ','split'};
end
This will give you a cell array of strings having the row and column shape or your original data.
To read an arbitrary line of text then break it up according the the formating information you have available. My example uses a single space character.
This uses regular expressions to define the separator. Regular expressions powerful but too complex to describe here. See the MATLAB help for regexp and regular expressions.
I have file names stored as follows:
>> allFiles.name
ans =
k-120_knt-500_threshold-0.3_percent-34.57.csv
ans =
k-216_knt-22625_threshold-0.3_percent-33.33.csv
I wish to extract the 4 values from them and store in a cell.
data={};
for k =1:numel(allFiles)
data{k,1}=csvread(allFiles(k).name,1,0);
data{k,2}= %kvalue
data{k,3}= %kntvalue
data{k,4}=%threshold
data{k,5}=%percent
...
end
There's probably a regular expression that can be used to do this, but a simple piece of code would be
data={numel(allFiles),5};
for k =1:numel(allFiles)
data{k,1}=csvread(allFiles(k).name,1,0);
[~,name] = fileparts(allFiles(k).name);
dashIdx = strfind(name,'-'); % find location of dashes
usIdx = strfind(name,'_'); % find location of underscores
data{k,2}= str2double(name(dashIdx(1)+1:usIdx(1)-1)); %kvalue
data{k,3}= str2double(name(dashIdx(2)+1:usIdx(2)-1)); %kntvalue
data{k,4}= str2double(name(dashIdx(3)+1:usIdx(3)-1)); %threshold
data{k,5}= str2double(name(dashIdx(4)+1:end)); %percent
...
end
For efficiency, you might consider using a single matrix to store all the numeric data, and/or a structure (so that you can access the data by name rather than index).
You simply need to tokenize using strtok multiple times (there is more than 1 way to solve this). Someone has a handy matlab script somewhere on the web to tokenize strings into a cell array.
(1) Starting with:
filename = 'k-216_knt-22625_threshold-0.3_percent-33.33.csv'
Use strfind to prune out the extension
r = strfind(filename, '.csv')
filenameWithoutExtension = filename(1:r-1)
This leaves us with:
'k-216_knt-22625_threshold-0.3_percent-33.33'
(2) Then tokenize this:
'k-216_knt-22625_threshold-0.3_percent-33.33'
using '_' . You get the tokens:
'k-216'
'knt-22625'
'threshold-0.3'
'percent-33.33'
(3) Lastly, for each string, tokenize using using '-'. Each second string will be:
'216'
'22625'
'0.3'
'33.33'
And use str2num to convert.
Strategy: strsplit() + str2num().
data={};
for k =1:numel(allFiles)
data{k,1}=csvread(allFiles(k).name,1,0);
words = strsplit( allFiles(k).name(1:(end-4)), '_' );
data{k,2} = str2num(words{1}(2:end));
data{k,3} = str2num(words{2}(4:end));
data{k,4} = str2num(words{3}(10:end));
data{k,5} = str2num(words{4}(8:end));
end
I have an array of strings:
dd = {'L','temp1','temp23','Reas'};
I would like to extract the numbers from the strings that contain any numbers (if that makes sense). So, the solution for this question should be 1 and 23.
How can I achieve this in matlab?
Here's part of the solution. Suppose
myString = 'temp23'
then the expression
str2double(a(isstrprop(a,'digit')))
will return
23
I haven't got the time to turn this into a function to deal with your array of strings but this should get you started.
#DennisJahruddin suggested the following completion of my answer. I haven't tested it thoroughly:
dd = {'L','temp1','temp23','Reas'};
ee = cellfun(#(a) str2double(a(isstrprop(a,'digit'))),dd);
ff = ee(~isnan(ee))