I've got a Matrix, let's say x, that contains seven values in exponential notation. Next i want to write this Variable to a textfuile, but without the exponential but with a decimal notation.
I tried str2num(num2str(exportdata, '%15.4f')); and fprintf but this only works for displayed data but not for storage as far as I know.
You can use fprinf to print directly to the file. For example:
v = [173524132746354.21542, 987678898521232.32547]
fid = fopen('file.txt','w')
fprintf(fid, '%0.2f, %0.2f', v)
fclose(fid)
Related
So, I have a series of display functions, ranging from x1 to x7. These all contain both strings and variables like:
x1 = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x2 = similar to above but with for example a value on the cross multiplication of the two scalars.
Instead of printing out each one through:
disp(x1);
disp(x2);
disp(x3);
I thought it would be possible to print them all out through a for loop or perhaps a nested for loop but I just can't figure out how to do it. I preferably don't want straight up solutions (I won't say no to them) but rather some hints or tips of possible.
A simple example solution would be to make a cell array and loop through it, or use celldisp() to display it. But if you want to print nicely, i.e. formatted specifically, to the command window you can use the fprintf function and format in line breaks. For example:
for displayValue = {x1, x2, x3, x4}
fprintf('%s\n', displayValue{1});
end
If you want more formatting options, such as precision, or fieldwidth, the formatspec code (%s in the example) has many configurations. You can see them on the fprintf helpdoc. The \n just tells the fprintf function to create a newline when it prints.
Instead of creating seven different variables (x1...x7), just create a cell array to hold all your strings:
x{1} = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x{2} = ['Some other statement with a value at the end: ',num2str(somevar)];
Now you can write a loop:
for iX = 1:length(x)
disp(x{iX})
end
Or use cellfun to display them without a for loop:
cellfun(#disp,x)
If you really want to keep them named x1...x7, then you can use an eval statement to get your variable names:
for iX = 1:7
disp(eval(['x' num2str(iX)]));
end
I want to convert an
fprintf output into a single array column and store into A
Additional Note: the Pij is a sparse matrix
for m = 1:nl
p = fb(m); q = tb(m);
fprintf('%8.3f\n', full(Pij(p,q)))
end
I'm trying the below code but it does not work. Appreciate your prompt solution as soon as possible . Thanks
A=sprintf('%8.3f\n', full(Pij(p,q)))
I want to import 100,000 digits of pi into matlab and manipulate it as a vector. I've copied and pasted these digits from here and saved them in a text file. I'm now having a lot of trouble importing these digits and rendering them as a vector.
I've found this function which calculates the digits within matlab. However, even with this I'm having trouble turning the output into a vector which I could then, for example, plot. (Plus it's rather slow for 100,000 digits, at least on my computer.)
Use textscan for that:
fid = fopen('100000.txt','r');
PiT = textscan(fid,'%c',Inf);
fclose(fid);
PiT is a cell array, so convert it to a vector of chars:
PiT = cell2mat(PiT(1));
Now, you want a vector of int, but you have to discard the decimal period to use the standard function:
Pi = cell2mat(textscan(PiT([1,3:end]),'%1d', Inf));
Note: if you delete (manually) the period, you can do that all in once:
fid = fopen('100000.txt','r');
Pi = cell2mat(textscan(fid,'%1d',Inf));
fclose(fid);
EDIT
Here is another solution, using fscanf, as textscan may not return a cell-type result.
Read the file with fscanf:
fid = fopen('100000.txt','r');
Pi = fscanf(fid,'%c');
fclose(fid);
Then take only the digits and convert the string as digits:
Pi = int32(Pi((Pi>='0')&(Pi<='9')))-int32('0');
Function int32 may be replaced by other conversion functions (e.g. double).
It can be done in one line.
When you modify your text file to just include the post-comma digits 14... you can use fscanf to get the vector you want.
pi = fscanf( fopen('pi.txt'), '%1d' ); fclose all
or without modifying the file:
pi = str2double( regexp( fscanf( fopen('pi.txt') ,'%1c'), '[0-9]', 'match'));
I am using NCSOStools for non-commutative computation in MATLAB. I create a matrix that I want to export and save to an Excel file. Here is my code:
clear all
clc
syms x
NCvars x
A=[x 2x 3x]
Normally I would be able to use the command xlswrite(filename,A) and save the matrix A to an excel file, but instead I am getting the error:
Input data must be a numeric, cell, or logical array.
Is there a simply way to save the NCpoly matrix A to Excel? I do not know if in general it is possible to change the data type to conform with the xlswrite command. Thanks very much.
I tried to save array of chars and it worked:
a = ['a', ' ','b']
xlswrite (test.xls, a)
may be, xlswrite does not support symbolic variables.
Your matrix A is symbolic, because this is how you defined x. You need to assign a definite value for A before passing it to xlswrite. This can be achieved either by substituting x with a concrete value using subs, or not defining A as symbolic in the first place.
As a workaround, you could use char to convert the symbolic expressions to a string as follows:
C = cell(size(A));
for k = 1:numel(A)
C{k} = char(A(k));
end
For an input of A = [x, 2 * x, 3 * x] you should get C = {'x', '2*x', '3*x'}. If you want to remove the asterisks (*), you could use strrep:
C = strrep(C, '*', '');
You can then pass the cell array of strings C to xlswrite.
I'm trying to write an octave program that will convert a .mat file to a .csv file. The .mat file has a matrix X and a column vector y. X is populated with 0s and 1s and y is populated with labels from 1 to 10. I want to take y and put it in front of X and write it as a .csv file.
Here is a code snippet of my first approach:
load(filename, "X", "y");
z = [y X];
basename = split{1};
csvname = strcat(basename, ".csv");
csvwrite(csvname, z);
The resulting file contains lots of really small decimal numbers, e.g. 8.560596795891285e-06,1.940359477121703e-06, etc...
My second approach was to loop through and manually write the values out to the .csv file:
load(filename, "X", "y");
z = [y X];
basename = split{1};
csvname = strcat(basename, ".csv");
csvfile = fopen(csvname, "w");
numrows = size(z, 1);
numcols = size(z, 2);
for i = 1:numrows
for j = 1:numcols
fprintf(csvfile, "%d", z(i, j));
if j == numcols
fprintf(csvfile, "\n");
else
fprintf(csvfile, ",");
end
end
end
fclose(csvfile);
That gave me a correct result, but took a really long time.
Can someone tell me either how to use csvwrite in a way that will write the correct values, or how to more efficiently manually create the .csv file.
Thanks!
The problem is that if y is of type char, your X vector gets converted to char, too. Since your labels are nothing else but numbers, you can simply convert them to numbers and save the data using csvwrite:
csvwrite('data.txt', [str2num(y) X]);
Edit Also, in the loop you save the numbers using integer conversion %d, while csvwrite writes doubles if your data is of type double. If the zeros are not exactly zeros, csvwrite will write them with scientific notation, while your loop will round them. Hence the different behavior.
Just a heads up your code isn't optimized for Matab / octave. Switch the for i and for j lines around.
Octave is in column major order so its not cache efficient to do what your doing. It will speed up the overall loop by making the change to probably an acceptable time