read the matrix elements of the loop and value them separately
이전 댓글 표시
A text file has a matrix with 2 columns and too many rows. The first element of this matrix in each line x, the second element y I want to say. How can I do this as a loop? I'll use these x and y in a calculation. Thanks in advance.
댓글 수: 3
pragnan nadimatla
2023년 6월 15일
As per my understanding, you have a matrix of 2 columns and multiple rows, and you want to store 1st element of every row and 2nd element of every row separately to use these for further computation.
You can do this by referring the below code. Here, I have created a random matrix of 10 rows and 2 columns and initialised 2 vectors “x” and “y” with zeros. I have iterated through all rows and 1st element and 2nd element have been extracted using matrix(i,1) and matrix(i,2).
% Create a random matrix of 10 rows and 2 columns
A = rand(10, 2);
% Initialize x and y vectors with zeros
x = zeros(10, 1);
y = zeros(10, 1);
% Loop over all rows of the matrix
for i = 1:size(A, 1)
% Read the first element of the i-th row into x
x(i) = A(i, 1);
% Read the second element of the i-th row into y
y(i) = A(i, 2);
end
Aakash
2023년 6월 15일
Please give a sample of how data looks in the text file
Dyuman Joshi
2023년 6월 15일
편집: Dyuman Joshi
2023년 6월 15일
It's not clear what exactly you want to do.
Do you want the data in 2 column assigned to 2 different variables? Then simply do this
%Let M be the array
x = M(:,1);
y = M(:,2);
There is no need of for loop for this.
If you want to do something else, then please specify your query (best with an example).
답변 (1개)
Sarthak
2023년 6월 15일
Hello Busra,
What I understand from your question is that you have a matrix of dimensions n*2 and you want to set the value of second element of every row to something. For this, you can write a function as mentioned below, and save it to some location with the same name as the function name, go to that loaction and run the function in the terminal.
Note : The code attached sets the second element of every row equal to the row index, you can modify it according to your requirement.
% The function sets the second column of a matrix equal to the index of the
% row
function outputMatrix = setSecondColumn(inputMatrix)
% Get the number of rows in the matrix
[rows,~] = size(inputMatrix);
% Loop through rows and set the second element of each row
for i=1:rows
inputMatrix(i,2) = i;
end
% Return the output matrix
outputMatrix = inputMatrix;
end
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!