read the matrix elements of the loop and value them separately
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!