Logical Input for embedded if loop.
Show older comments
Below is the assignment: 1. Create a 4 x 8 matrix of randomly generated numbers. 2. Loop through all rows and columns, and test whether each element is greater than 0.5. 3. Report the results of the test along with the value of the matrix ele- ment and its row-column position. For example, your Matlab script should print The 3rd row and 8th column has a value of 0.42345 and is not bigger than 0.5. 4. Make sure to add exceptions to print out 1st, 2nd, and 3rd, instead of 1th, 2th, and 3th. 5. Put this code into a separate function that you can call from the com- mand line with two inputs, corresponding to the number of rows and the number of columns of the matrix.
The following code has an issue in the if loop where it states that the input and output for a logical comparator are not balanced. However, I have added 1 one on each side. A troubleshoot would be appreciated
%4.7 Excercises Cohen text
rand_matrix_A = rand ([4,8]);
[row,col,v] = find (rand_matrix_A > 0.5);
ind_row_col= horzcat (row, col);
for i = 1 : size (ind_row_col, 1);
% exceptions for row index
if ind_row_col(i,1)== 1 or ind_row_col(i,2)== 1;
num_modifier1 = 'st';
disp (['The ' num2str(ind_row_col(i,1)) num_modifier1 ' row and ' num2str(ind_row_col (i, 2)) num_modifier1 ' column has a value of ' num2str(rand_matrix_A (ind_row_col(i,1), ind_row_col (i, 2))) ' and is not bigger than 0.5'])
end
if ind_row_col(i,1)== 2 or ind_row_col(i,2) == 2;
num_modifier2 = 'nd';
disp (['The ' num2str(ind_row_col(i,1)) num_modifier2 ' row and ' num2str(ind_row_col (i, 2)) num_modifier2 ' column has a value of ' num2str(rand_matrix_A (ind_row_col(i,1), ind_row_col (i, 2))) ' and is not bigger than 0.5'])
end
if ind_row_col(i,1)== 3 or ind_row_col(i,2) == 3;
num_modifier3 = 'rd';
disp (['The ' num2str(ind_row_col(i,1)) num_modifier3 ' row and ' num2str(ind_row_col (i, 2)) num_modifier3 ' column has a value of ' num2str(rand_matrix_A (ind_row_col(i,1), ind_row_col (i, 2))) ' and is not bigger than 0.5'])
end
disp (['The ' num2str(ind_row_col(i,1)) 'th row and ' num2str(ind_row_col (i, 2)) 'th column has a value of ' num2str(rand_matrix_A (ind_row_col(i,1), ind_row_col (i, 2))) ' and is not bigger than 0.5'])
end
Accepted Answer
More Answers (1)
Guruprasad Madhale Jadav
on 6 Jun 2018
0 votes
I have attached a file with the working example. Chears :)
1 Comment
Guruprasad Madhale Jadav
on 6 Jun 2018
Edited: Guruprasad Madhale Jadav
on 6 Jun 2018
to call it as a function add the following code on the top of the script and remove the assigned constants (in this case file name is Chapter4a.m)
function [] = filename(rows, columns) % code
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!