How to add scalar to empty matrix?

3 views (last 30 days)
Random goose
Random goose on 9 Dec 2018
Edited: Stephen23 on 10 Dec 2018
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
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.
Random goose
Random goose on 10 Dec 2018
Thank you for your response. I think I just used a bad example to motivate my question. I was wondering if there is a special command that would allow me to convert empty matrices to zero, so that the addition/multiplication/subtraction with a scalar will go through. I am trying to avoid "if isempty()" statements, which would be another possible solution suggested on the forum.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 10 Dec 2018
Edited: Stephen23 on 10 Dec 2018
Where val is possibly empty, and the ouput should be a scalar:
tmp = [val,0];
tmp(1)
If the output could be non-scalar, then if with isempty is probably the clearest solution.

More Answers (1)

KSSV
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.
  1 Comment
Random goose
Random goose on 10 Dec 2018
Thank you for your response. Using "if isempty()" is a good solution, but I wonder if this could slow down the computation. I am running this on a more complicated structure that has quite a few of conditional statements. If possible, I would like to avoid if statements. Is there any command for converting empty matrices into a zero scalar?

Sign in to comment.

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!