A:B with two matrices instead of scalars
Show older comments
I have two matrices a = [1;2;3;4;5;6] and b = [5;6;7;8;9;10].
I want to compute [1:5;2:6;3:7;4:8;5:9;6:10] as a whole matrix. But want it in a for loop so it is not computed manually for each row.
Currently, I have used the code:
for i = [1:6]
c = [a(i,1):b(i,1)];
end
This only does it for the last term (ie 6:10) but not the 1st, 2nd, 3rd, 4th and 5th term.
How can it be done like this?
Answers (2)
Walter Roberson
on 5 Aug 2018
c = (a(1):b(1)) + (a - a(1));
Requires R2016b or later, and requires that the difference b-a remains constant.
For earlier releases,
c = bsxfun(@plus, (a(1):b(1)) , a-a(1));
Image Analyst
on 6 Aug 2018
Walter gave the more MATLABy way of doing it. If you really want a for loop way of doing it, here is a partially robust way of doing it.
a = [1;2;3;4;5;6]
b = [5;6;7;8;9;10]
numColumns = max(b-a) + 1 % Assume a and b are integers
maxRows = min([length(a), length(b)])
c = zeros(maxRows, numColumns)
for row = 1 : maxRows % Assume a and b are the same length, otherwise get error.
% Assume a(row) : b(row) is the same number of elements for every row,
% otherwise you'll get an error.
c(row, :) = a(row) : b(row);
end
c % Report results to command window.
Again, like Walter's solution, it assumes certain things.
Categories
Find more on Loops and Conditional Statements 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!