Logical Input for embedded if loop.
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
Guruprasad Madhale Jadav
2018년 6월 6일
0 개 추천
I have attached a file with the working example. Chears :)
댓글 수: 1
Guruprasad Madhale Jadav
2018년 6월 6일
편집: Guruprasad Madhale Jadav
2018년 6월 6일
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
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!