For loop and if else statements with multiple conditions

조회 수: 8 (최근 30일)
Henrik Oestby
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
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
  댓글 수: 1
Henrik Oestby
Henrik Oestby 2020년 8월 20일
Thank you!!
This is great and helped me tremendously!
Henrik

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by