How can I equate a character to an integer?
3 views (last 30 days)
Show older comments
I'm trying to write a function to find the summation of an m by n matrix.
if true
% code
end
m = 3.6
n = 4
if m == true && n == true
for i = 1:m
for j = 1:n
A(i,j) = i + j;
end
end
else
disp('both m and n must be positive integers.')
end
end
4 Comments
Accepted Answer
Image Analyst
on 30 Aug 2018
Try this. I do it both your way, and a more MATLABy way with meshgrid that avoids explicit loops.
m = 3 % Rows or y
n = 4 % Columns or x
if rem(m, 1) == 0 && rem(n, 1) == 0 && m >= 1 & n >= 1
% Double for loop way:
A = zeros(m, n);
for row = 1 : m
for col = 1 : n
A(row, col) = row + col;
end
end
% Vectorized, MATLAB way:
[C, R] = meshgrid(1 : n, 1 : m)
B = C + R
else
uiwait(errordlg('Both m and n must be positive integers.'))
end
A % Show in command window.
You get
B =
2 3 4 5
3 4 5 6
4 5 6 7
A =
2 3 4 5
3 4 5 6
4 5 6 7
4 Comments
madhan ravi
on 30 Aug 2018
If the answer works accept the answer so that you appreciate the person’s effort and let others know there is a correct answer for the question.
More Answers (0)
See Also
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!