How to add scalar to empty matrix?
3 views (last 30 days)
Show older comments
Can I make an empty matrix behave as zero when adding/subtracting/ a scalar with such an empty matrix?
Suppose you have the following for loop
result = zeros(5,1);
for k=1:5
result(k) = k^2 + ones(k-1,1)*5;
end
On the very first loop I will have 1^2 + []*5, and this will return an empty vector. I can obviously change the starting point for k to 2 to avoid this issue. However the problem I have is a more complicated version, and in some cases the starting point for the loop will be random. I would like to obtain k^2+[]*5 = k^2; treat the empty matrix as a zero, but matlab will just return an empty vector. Is there any way of converting an empty matrix into zero, and keeping the matrix if its not empty?
2 Comments
Stephen23
on 10 Dec 2018
Edited: Stephen23
on 10 Dec 2018
You noticed the flaw in your code for k=0, but notice also that your code will not work for any k>1, because on this line:
result(k) = k^2 + ones(k-1,1)*5;
you try to allocate the RHW into one element of the LSH array result, so this will not work if the RHY is a two element vector, or a three element vector, etc., because you cannot force multiple elements of an array into one element of another array. An numeric array element contains one value, and that is all.
In fact your code will only work when k=1.
Accepted Answer
More Answers (1)
KSSV
on 10 Dec 2018
result = cell(5,1);
for k=1:5
k1 = ones(k-1,1)*5 ;
if isempty(k1)
result{k} = k^2 ;
else
result{k} = k^2 + k1 ;
end
end
YOu cannot put the rsult into a matrix......store them in a cell.
See Also
Categories
Find more on Data Type Conversion 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!