Effacer les filtres
Effacer les filtres

How to loop over column?

4 vues (au cours des 30 derniers jours)
dwi maulida
dwi maulida le 29 Avr 2021
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

Réponses (1)

Pavan Sahith
Pavan Sahith le 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);
% Optional: Handle the case where all values in a column are the same
input(:,j) = 0.5; % This is just an example decision
To verify the results, you can print the modified input matrix or inspect specific columns to ensure they have been normalized as expected.
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.


En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by