For loop and if else statements with multiple conditions
3 次查看(过去 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
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).
采纳的回答
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!