Take a variable with unkown array length consisting of only numbers, and assign each number in that array to an independent variable?

1 view (last 30 days)
Hello,
I have a large matrix Y of only numbers, mostly zeroes. I am using the code below to remove all zeroes and output only the non-zero numbers in the form of an array under variable C:
Y(Y == 0) = [];
c = unique(Y)
Where I am running into difficulty, is the next part: I would like to assign each number in c to a distinct variable.
For example, if:
c = [5 10 15 20 25 30]
I would like to then output,
d = 5,
e = 10,
f = 15,
g = 20,
h = 25,
i = 30
The reason behind this is I then need to multiply each of these by a number array.
For example:
numarray = -3:3;
d1 = d*numarray;
e1 = e*numarray;
f1 = f*numarray;
g1 = g*numarray;
h1 = h*numarray;
i1 = i*numarray;
My constraint: - I don't know how many integers c will spit out in the original array, it could be 6 in the above 5,10,15,20,25,30 example, or it can be just 1 or even 20. My code needs to account for any given size.
There may be a different or easier way to go about this that I haven't thought of, if you have a solution to this please do let me know. I'm sure I'm not the only one who's has come across this issue, it seems standard enough.
Thanks! Niket

Accepted Answer

Steven Lord
Steven Lord on 20 Jul 2015
DO NOT DO THIS!
You are correct that you're not the only one who has asked how to do that. In fact, the first question in the Programming section of the FAQ explains why this is a BAD IDEA and alternatives you should use instead.
  1 Comment
Niket Kadakia
Niket Kadakia on 22 Jul 2015
Edited: Niket Kadakia on 22 Jul 2015
Thank you Steven, I learned my lesson & solved my problem. I will not try to create new variables every time. I can work within a variables cell's cell, & will continue to take it deeper like some kind of Matlab-inception! Thanks again!

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 20 Jul 2015
  1 Comment
Niket Kadakia
Niket Kadakia on 22 Jul 2015
Edited: Niket Kadakia on 22 Jul 2015
Thank you Walter for linking me directly to the section indicated by Steven Lord. Although I didn't use the line you provided (I didn't want a single full-on matrix), this worked out well for me:
for i=1:length(c); d{i} = c(i)*numarray; end
My end result for "d" is a [1xA 1xA ... 1xA] arrays within an array. The number of 1xA's in "d" is equal to however many numbers were contained in "c". The A of course was the length of numarray. Opening up each 1xA I could see the respective "c(#) value multiplied by each numarray(#). Hope that made sense & thank you very much!

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!