MATLAB Answers

Using a for loop to extract values from a matrix

1 view (last 30 days)
Lovisa Norlin
Lovisa Norlin on 7 May 2021
Commented: Lovisa Norlin on 7 May 2021
Hello!
I have a 5x12 matrix. The purpose of the matrix is to show different temperatures during every month of a year in 5 different cities
A = [ 1 2 3 4 5 6 7 8 9 10 11 12 ; 1 2 3 4 5 6 7 8 9 10 11 12 ; 1 2 3 ... an so on]
Now what I want to do is "seperate" temperatures that are under a certain degree, for example if the temperature drops under 4 degrees celsius i want this to be displayed in the command window.
I should showcase temperatures of 1 2 3 for all the 5 cities.
I tried something like this:
for i = A(1:end)
if i < 4
disp('To cold')
end
end
I do not resive any error messages, but nothing happens, at all. It's obvious my MatLab skills are non existant so I'd really appriciate the help!!

Answers (1)

Cris LaPierre
Cris LaPierre on 7 May 2021
Typically this is done using your loop counter to index into your vector.
You can learn more about indexing in Ch 5 of MATLAB Onramp. Of course, you will need to set up your for loop correctly so that the loop counter is meaningful. See Ch 13 for that.

Community Treasure Hunt

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

Start Hunting!

Translated by