Store integers from a text file into variable arrays - matlab

I need to plot some coordinate of x, y in MATLAB using some text file.
and I get a problem with reading it using a for loop.
I can figure it in Python but I need help in converting it in MATLAB.
This is some code in Python
file = open("6.txt", "r")
x = []
y = []
z = []
for i in file.readlines()[::]:
if i[0] == "(":
jam = i.strip('()').split(",")
x.append(float(jam[0]))
y.append(float(jam[1]))
jam = i.strip('()\n').split(",")
z.append(float(jam[2]))
'''
but in Matlab I initially start with this code
fileID = fopen('1.txt', 'r+');
formatSpec = '%s';
for i = fscanf(fileID, '%s')[::]
in Python result is
x = [1.154545 1.265648 ..... 1.56849]
Y = [1.0 1.5655 1.61662 ..... 1.0]

You can try something like:
content=readmatrix('1.txt') %read the entire content as a matrix
x=content(:1) %extract the first column
y=content(:2) %extract the second column
plot(x,y) %plot the data
I cannot test the above code right now, this is why I commented every line that I wrote. But the algorithm remains.

Related

How to store .csv data and calculate average value in MATLAB

Can someone help me to understand how I can save in matlab a group of .csv files, select only the columns in which I am interested and get as output a final file in which I have the average value of the y columns and standard deviation of y axes? I am not so good in matlab and so I kindly ask if someone to help me to solve this question.
Here what I tried to do till now:
clear all;
clc;
which_column = 5;
dirstats = dir('*.csv');
col3Complete=0;
col4Complete=0;
for K = 1:length(dirstats)
[num,txt,raw] = xlsread(dirstats(K).name);
col3=num(:,3);
col4=num(:,4);
col3Complete=[col3Complete;col3];
col4Complete=[col4Complete;col4];
avgVal(K)=mean(col4(:));
end
col3Complete(1)=[];
col4Complete(1)=[];
%columnavg = mean(col4Complete);
%columnstd = std(col4Complete);
% xvals = 1 : size(columnavg,1);
% plot(xvals, columnavg, 'b-', xvals, columnavg-columnstd, 'r--', xvals, columnavg+columstd, 'r--');
B = reshape(col4Complete,[5000,K]);
m=mean(B,2);
C = reshape (col4Complete,[5000,K]);
S=std(C,0,2);
Now I know that I should compute mean and stdeviation inside for loop, using mean()function, but I am not sure how I can use it.
which_column = 5;
dirstats = dir('*.csv');
col3Complete=[]; % Initialise as empty matrix
col4Complete=[];
avgVal = zeros(length(dirstats),2); % initialise as columnvector
for K = 1:length(dirstats)
[num,txt,raw] = xlsread(dirstats(K).name);
col3=num(:,3);
col4=num(:,4);
col3Complete=[col3Complete;col3];
col4Complete=[col4Complete;col4];
avgVal(K,1)=mean(col4(:)); % 1st column contains mean
avgVal(K,2)=std(col4(:)); % 2nd column contains standard deviation
end
%columnavg = mean(col4Complete);
%columnstd = std(col4Complete);
% xvals = 1 : size(columnavg,1);
% plot(xvals, columnavg, 'b-', xvals, columnavg-columnstd, 'r--', xvals, columnavg+columstd, 'r--');
B = reshape(col4Complete,[5000,K]);
meanVals=mean(B,2);
I didn't change much, just initialised your arrays as empty arrays so you do not have to delete the first entry later on and made avgVal a column vector with the mean in column 1 and the standard deviation in column 1. You can of course add two columns if you want to collect those statistics for your 3rd column in the csv as well.
As a side note: xlsread is rather heavy for reading files, since Excel is horribly inefficient. If you want to read a structured file such as a csv, it's faster to use importdata.
Create some random matrix to store in a file with header:
A = rand(1e3,5);
out = fopen('output.csv','w');
fprintf(out,['ColumnA', '\t', 'ColumnB', '\t', 'ColumnC', '\t', 'ColumnD', '\t', 'ColumnE','\n']);
fclose(out);
dlmwrite('output.csv', A, 'delimiter','\t','-append');
Load it using csvread:
data = csvread('output.csv',1);
data now contains your five columns, without any headers.

Multipage Tiff write in MATLAB doesn't work

I'm reading in a Tiff using the below function, which works fine, but when I try to use my write function to write that same Tiff back to a different file, it's all 255's. Does anyone know how to fix this? Thanks, Alex.
function Y = tiff_read(name)
% tiff reader that works
info = imfinfo(name);
T = numel(info);
d1 = info(1).Height;
d2 = info(1).Width;
Y = zeros(d1,d2,T);
for t = 1:T
temp = imread(name, t, 'Info',info);
Y(:,:,t) = temp(1:end,1:end);
end
% Tiff writer that doesn't work
function tiff_write(Y,name)
% Y should be 3D, name should end in .tif
T = size(Y,3);
imwrite(Y(:,:,1),name);
for t = 2:T
imwrite(Y(:,:,t),name,'WriteMode','append');
end
Try using this line :
Y = zeros(d1,d2,T,'uint16');
instead of this one:
Y = zeros(d1,d2,T);
Your data are likely in uint16 format and when you export you clip the maximum value to 255 (uint8), which makes pixel with values greater than 255 (a LOT of them if your data is in uint16) appear white.
Otherwise you might want to use this line:
function tiff_write(Y,name)
% Y should be 3D, name should end in .tif
for t = 2:T
imwrite(Y(:,:,t)/255,name,'WriteMode','append');
end

Reading data from a Text File into Matlab array

I am having difficulty in reading data from a .txt file using Matlab.
I have to create a 200x128 dimension array in Matlab, using the data from the .txt file. This is a repetitive task, and needs automation.
Each row of the .txt file is a complex number of form a+ib, which is of form a[space]b. A sample of my text file :
Link to text file : Click Here
(0)
1.2 2.32222
2.12 3.113
.
.
.
3.2 2.22
(1)
4.4 3.4444
2.33 2.11
2.3 33.3
.
.
.
(2)
.
.
(3)
.
.
(199)
.
.
I have numbers of rows (X), inside the .txt file surrounded by brackets. My final matrix should be of size 200x128. After each (X), there are exactly 128 complex numbers.
Here is what I would do. First thing, delete the "(0)" types of lines from your text file (could even use a simple shells script for that). This I put into the file called post2.txt.
# First, load the text file into Matlab:
A = load('post2.txt');
# Create the imaginary numbers based on the two columns of data:
vals = A(:,1) + i*A(:,2);
# Then reshape the column of complex numbers into a matrix
mat = reshape(vals, [200,128]);
The mat will be a matrix of 200x128 complex data. Obviously at this point you can put a loop around this to do this multiple times.
Hope that helps.
You can read the data in using the following function:
function data = readData(aFilename, m,n)
% if no parameters were passed, use these as defaults:
if ~exist('aFilename', 'var')
m = 128;
n = 200;
aFilename = 'post.txt';
end
% init some stuff:
data= nan(n, m);
formatStr = [repmat('%f', 1, 2*m)];
% Read in the Data:
fid = fopen(aFilename);
for ind = 1:n
lineID = fgetl(fid);
dataLine = fscanf(fid, formatStr);
dataLineComplex = dataLine(1:2:end) + dataLine(2:2:end)*1i;
data(ind, :) = dataLineComplex;
end
fclose(fid);
(edit) This function can be improved by including the (1) parts in the format string and throwing them out:
function data = readData(aFilename, m,n)
% if no parameters were passed, use these as defaults:
if ~exist('aFilename', 'var')
m = 128;
n = 200;
aFilename = 'post.txt';
end
% init format stuff:
formatStr = ['(%*d)\n' repmat('%f%f\n', 1, m)];
% Read in the Data:
fid = fopen(aFilename);
data = fscanf(fid, formatStr);
data = data(1:2:end) + data(2:2:end)*1i;
data = reshape(data, n,m);
fclose(fid);

Reading a text file and plotting it in 3D

I want to read in a text file that contains some strings but mostly numbers. I want to be able to ignore the strings and only look at the numbers. I want to plot those values on a 3D plane. The data looks like this:
Tech4:<152.266724,173.189377,27.995975>
<117.880638,156.116531,27.999983>
<129.849899,59.195660,27.999983>
<249.321121,60.605404,27.999983>
<224.120361,139.072739,28.000668>
<171.188950,143.490921,56.933430>
<171.188950,143.490921,83.548088>
<171.188950,143.490921,27.999985>
I believe to read in a file is just:
File = textread('testFile.txt');
How can I only look at those values and then plot it.
Thanks!
fid = fopen([pathname,filename]);
tline = fgetl(fid);
CX = [];
CY = [];
CZ = [];
while ischar(tline)
% skip < and >
tline = substr(tline, 1, length(tline)-2)
% extract numbers
temp = textscan(tline,'%n%n%n', 'delimiter',',');
CX(end+1,:) = [temp(1)];
CY(end+1,:) = [temp(2)];
CZ(end+1,:) = [temp(3)];
tline = fgetl(fid);
end
fclose(fid);
and then plot it using
plot3(CX, CY, CZ)
function call.
Add the check for "Tech4:" at the beginning however...
I think you can also directly use textscan in a one-liner:
fid = fopen('testFile.txt');
data = textscan(fid,'%*s%f,%f,%f');
fclose(fid);
this loads the values from all rows with the specified format into the variable data.
no matlab around to test it out though.
fscanf is an option to, the same kind of parameters as textscan.
EDIT: typo, you want to detect floats (%f) of course, and not integers (%d)
EDIT2: got matlab and tested it out, this works here for your sample input ^^
fid = fopen('testFile.txt');
data = textscan(fid,'%*s%f%f%f','Delimiter',',<>')
fclose(fid);

Matlab -- Conversion to double from cell is not possible

Can someone tell me why I am receiving this error --
??? The following error occurred converting from cell to
double:
Error using ==> double
Conversion to double from cell is not possible.
Error in ==> test at 18
CX(end+1,:) = temp(1);
Here is the code:
file = fopen('C:\Program Files (x86)\Notepad++\testFile.txt'); % open text file
tline = fgetl(file); % read line by line and remove new line characters
%declare empty arrays
CX = [];
CY = [];
CZ = [];
while ischar(tline) % true if tline is a character array
temp = textscan(fid,'%*s%f%f%f','Delimiter',',<>'); % loads the values from all rows with the specified format into the variable data
CX(end+1,:) = temp(1);
CY(end+1,:) = temp(2);
CZ(end+1,:) = temp(3);
tline = fgetl(file);
end
fclose(file); % close the file
plot3(CX, CY, CZ) % plot the data and label the axises
xlabel('x')
ylabel('y')
zlabel('z')
grid on
axis square
Quick guess: does using curly braces help?
CX(end+1,:) = temp{1}
Use cell2mat to convert from a cell array (what textscan returns) to a numeric array, which you can use (like append to, in your case) with other numeric arrays.
I would also recommend using vertcat rather than the approach you've taken to concatenating:
CX = vertcat(CX, cell2mat(temp(1)));
Or, you could read all 3 values in to a row and concatentate into a N-by-3 matrix instead... lots of options.