Filter löschen
Filter löschen

How can i store the two variable in an excel sheet in every iteration of the loop ?

9 Ansichten (letzte 30 Tage)
Suppose We have two variables, y and z. In every iteration of a loop, y and z change their values. We must store the y and z values column-wise for every iteration in an Excel sheet. I attached an example of the code. So We need to store data in a D matrix(50 by 100 (Row by column)). Can you provide a solution to this problem? Your help will be appreciated.
Thank you for your help.
clc
clear
close all
x = rand(1,50).';
n = length(x);
for i = 1:n
y = sin(x);
z = cos(x);
D = [y,z];
end

Akzeptierte Antwort

Rahul
Rahul am 31 Mai 2023
Bearbeitet: Rahul am 1 Jun. 2023
Assuming that you simply need to arrange the values of D (x, y column-wise concatenated) of each iteration column-wise, without labelling the columns, we could append 50 'D' values of each iteration to an initially empty matrix T to form a 50x100 matrix, and finally insert this matrix 'T' into an excel spreadhseet with fileName, say 'sample.xlsx' (or .xls), which will be created on the currently open folder, by appending two lines on your provided code snippet:
A good tip form @Walter Roberson, to pre-allocate dimensions for the 'T' matfrix for better efficiency:
clc
clear
close all
% Initializing Random variable x
x = rand(1,50).';
n = length(x);
T = zeros(n, 2*n);
% Looping over 50 iterations
for i = 1:n
y = sin(x);
z = cos(x);
% Storing current iteration values
T(:, 2*i - 1) = y;
T(:, 2*i) = z;
end
% Writing to an excel spreadhseet
fileName = 'sample.xlsx';
writematrix(T, fileName);
You can even refer to the writematrix function documentation, to read further about the function or customize it as per your needs.
  3 Kommentare
Walter Roberson
Walter Roberson am 1 Jun. 2023
T(:, 2*n - 1) = y;
wrong index. n is constant relative to that loop, so you are always writing to the same locations in the loop.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Diwakar Diwakar
Diwakar Diwakar am 31 Mai 2023
% Initialize the matrix D
D = zeros(50, 100);
% Loop for 50 iterations
for i = 1:50
% Calculate random values for y and z
y = rand();
z = rand();
% Store y and z values in matrix D
D(i, 1) = y;
D(i, 2) = z;
end
% Save the matrix D to a CSV file
filename = 'data.csv';
csvwrite(filename, D);

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by