For loop and if else statements with multiple conditions

2 次查看(过去 30 天)
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 个评论
Geoff Hayes
Geoff Hayes 2020-8-19
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 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
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by