How to replace columns in a datafile after performing mathematical operations to them?

I have a datafile having 40 columns and have to divide first column with a constant number (let say 5) and rest 39 columns with a different number (i.e. 7). So, I want to replace all the columns in a new datafile. Can you suggest any short method for it.
I am trying the following code but its not replacing the column, and just appending a column according to last given mathematical operation (i.e. here appending the new calculated 3rd column to the first column).
x=5; % a constant
y=7; %another constant
a = textread('file1.txt');
a1 = a(:,1)/x;
a2 = a(:,2)/y;
a3 = a(:,3)/y; %third column
save ('New_file1.txt','-ascii')
type('New_file1.txt')

 Respuesta aceptada

x=5; % a constant
y=7; %another constant
a = readmatrix('file1.txt');
disp(a)
1 2 3 4 5 6 7 8 9 10 11 12
new_a = a;
new_a(:,1) = new_a(:,1)/x;
new_a(:,2:end) = new_a(:,2:end)/y;
disp(new_a)
0.2000 0.2857 0.4286 0.5714 1.0000 0.8571 1.0000 1.1429 1.8000 1.4286 1.5714 1.7143
writematrix(new_a,'New_file1.txt')
type('New_file1.txt')
0.2,0.285714285714286,0.428571428571429,0.571428571428571 1,0.857142857142857,1,1.14285714285714 1.8,1.42857142857143,1.57142857142857,1.71428571428571

6 comentarios

Thanks, but here writematrix is giving the data file separated by comma, whereas I want to store it in the previous column format.
How to do that?
there is a Delimiter option for writematrix()
@Shivu: As @Walter Roberson points out, try using ' ' (space) or '\t' (tab) or whatever the delimiter is in your original file (which I don't have):
new_a = rand(3);
writematrix(new_a,'New_file1.txt','Delimiter',' ')
type('New_file1.txt')
0.629923049782379 0.752624146887233 0.888350208105833 0.693355864220194 0.611977293643469 0.996243963795178 0.252144826948704 0.270950749648683 0.0546494299877862
writematrix(new_a,'New_file1.txt','Delimiter','\t')
type('New_file1.txt')
0.629923049782379 0.752624146887233 0.888350208105833 0.693355864220194 0.611977293643469 0.996243963795178 0.252144826948704 0.270950749648683 0.0546494299877862
delimiter is not exactly placing it in columns. The output columns are quite messed up like this (even after using delimiter and tab)
0.4 0 6.508137e-06 0.08816902 0 -1.038636e-05 -1.35101e-05 6.832663e-09 5.346719e-05 1.111237e-06 -1.685898e-15 2.444716e-30 8.885579e-05 9.178685e-05 2.201578e-05 1.908472e-05
0.4666667 0 6.508137e-06 0.08816902 0 -1.011229e-05 -1.344511e-05 8.215198e-09 5.345097e-05 1.289439e-06 -2.139239e-15 -7.48446e-30 8.755713e-05 9.05559e-05 2.142161e-05
Thanks to both of you, now I got it.
Glad you got it figured out!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

el 28 de Mayo de 2022

Comentada:

el 28 de Mayo de 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by