How to loop over column?
조회 수: 2 (최근 30일)
이전 댓글 표시
i have matrix input(4,12). i want to do loop over column but it only work for last column.
how do i get the loop correctly?
for j=1:12
xaij1=((input(:))-min(input(:,j)))/(max(input(:))-min(input(:)));
xaij=reshape(xaij1,[4,12]);
end
댓글 수: 0
답변 (1개)
Pavan Sahith
2024년 5월 14일
Hello ,
I assume that you want to normalize each column of the input matrix individually, but there's a misunderstanding in how you're applying the normalization and the loop.
input(:) is used, which converts the whole matrix into a column vector, affecting all columns at once rather than column-by-column. You should be using input(:,j) to focus on the current column in the loop.
The reshaping at each iteration is unnecessary if you're only modifying one column at a time. Instead, you can directly assign the normalized values back to the original column.
create some sample data for a 4x12 matrix to test the normalization code provided.
input = rand(4, 12) * 100;
apply the normalization loop to this input matrix:
for j = 1:12
% Normalize each column individually
colMin = min(input(:,j));
colMax = max(input(:,j));
% Check if colMax is equal to colMin to avoid division by zero
if colMax ~= colMin
input(:,j) = (input(:,j) - colMin) / (colMax - colMin);
else
% Optional: Handle the case where all values in a column are the same
input(:,j) = 0.5; % This is just an example decision
end
end
To verify the results, you can print the modified input matrix or inspect specific columns to ensure they have been normalized as expected.
disp(input);
I used 'rand' function to create some sample data. You can refer to the following MathWorks documentation to know more about
Hope this will help you in moving forward.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!