# For loop and if else statements with multiple conditions

7 ビュー (過去 30 日間)
Henrik Oestby 2020 年 8 月 19 日
コメント済み: Henrik Oestby 2020 年 8 月 20 日
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 件のコメント表示非表示 1 件の古いコメント
Henrik Oestby 2020 年 8 月 19 日
Thank you, Geoff! I will fiddle around with two for loops, and see where it takes me.
I appreciate the response!
Henrik

サインインしてコメントする。

### 採用された回答

Binbin Qi 2020 年 8 月 19 日
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
##### 1 件のコメント表示非表示 なし
Henrik Oestby 2020 年 8 月 20 日
Thank you!!
This is great and helped me tremendously!
Henrik

サインインしてコメントする。

### カテゴリ

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

R2019a

### Community Treasure Hunt

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

Start Hunting!

Translated by