# How to loop over column?

4 Ansichten (letzte 30 Tage)
dwi maulida am 29 Apr. 2021
Beantwortet: Pavan Sahith am 14 Mai 2024
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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (1)

Pavan Sahith am 14 Mai 2024
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
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by