How to initialize a new matrix of the same type as an existing variable?
Show older comments
I'm writing a function that I want to support either numerical or symbolic inputs. It takes in a matrix, initializes a new matrix, then defines it in a for loop. If the input is a syms variable, I'd like to be able to initialize a syms matrix and populate it. If the input is a double, I want to initialize a matrix of doubles. Is there any function that can do this? I can think of some work-arounds that would suffice for this particular example (mostly just not initializing a new matrix before populating in a loop, or setting the new matrix equal to the incoming one before populating) but I'd like to find a neater way to do it.
Accepted Answer
More Answers (1)
J. Alex Lee
on 6 Mar 2020
I am not sure if this works for symbolic type, but you can initialize an array of arbitrary type by specifying the "last" element first, so if you do
clear;
A(10) = 1
A will end up being a 1x10 array of type double, or of type anything that you put in place of 1.
So in a loop, if you know the extents of your desired final array in each dimension, you can step backwards to 1
for j = 10:-1:1
for i = 20:-1:1
A(j,i) = ...
end
end
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!