For loop and if else statements with multiple conditions

8 views (last 30 days)
Hi,
I am new to Matlab and am currently working on some MatLab exercises, and one of the excersices asks for the following:
Create a 4x8 matrix with random numbers
Loop through the rows and columns and test whether each element is greater than 0.5
Report the results of the test with the matrix element value and the row-columns position. (i.e "The 3rd row and the 8th columns has a value of x and is greater than 0.5").
Make sure to add exceptions to print out 1st 2nd 3rd, instead of 1th, 2th, 3th etc.
I can do the first two excersies, but I struggle with the two last lines. How can I create a for loop that gives me the column-row position, whether the matrix element is greater than 0.5, and also prints out the correct "1st, 2nd etc" without going into extremely tiresome and long "if elseif elseif elseif......", which I am currenty stuck on.
Any tips on how to solve this?
  2 Comments
Geoff Hayes
Geoff Hayes on 19 Aug 2020
Herik - I suspect that the exercise is trying to get you to use two for loops (an outer and inner loop) so that you iterate over the rows and the columns. You would then use the row and column indices in your fprintf statement...all without using if statements (except for the comparison to 0.5).
Henrik Oestby
Henrik Oestby on 19 Aug 2020
Thank you, Geoff! I will fiddle around with two for loops, and see where it takes me.
I appreciate the response!
Henrik

Sign in to comment.

Accepted Answer

Binbin Qi
Binbin Qi on 19 Aug 2020
clear;clc;close all
[m, n] = deal(4, 8);
matrix_data = rand(m, n);
num = ['1st','2nd','3rd', sprintfc('%dth', 4:8)];
for i = 1 : m
for j = 1 : n
if matrix_data(i, j) > 0.5
fprintf('The %s row and the %s columns has a value of %6.2f and is greater than 0.5\n',...
num{i}, num{j}, matrix_data(i, j));
end
end
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!