sajad
sajad

Reputation: 1082

Use a counter for nonindexed variables and putting them in an array

I have 20 cities in Matlab.

city1='arad'   
...  
city20='neamt'  

My question is, how to use a counter as 'i' for call my cities and put them all in an array.

I have tried these:

    function [city,neighbor,list]=m()  
    main; //referred to my cities name in main.m  
    for i=1:20 //i used a loop   
    city=cityi  // what i whises is city1...city20 
    list=[city]// i want all cities in an array!  
    end 

But it doesn't work.

Upvotes: 2

Views: 71

Answers (2)

rayryeng
rayryeng

Reputation: 104474

If you want to avoid using eval, you can save all of your workspace variables that have city at the beginning of them to a temporary .mat file, then reload the .mat file by storing its contents into a variable. This variable would essentially be a structure where each field is named according to the variables that you saved from your workspace. Once you load this structure in, you can use struct2cell to convert each structure field into a separate entry in a cell array. As Kamtal has noted in his post, it is suggested that you put all of these in a cell array, especially since the length of each city will change per variable.

When you load in the .mat file, the way the structure fields are ordered should be numerically sorted, and so we don't have to worry about ordering anything. If you are truly concerned, consider using orderfields to ensure that the fields are ordered numerically.... but I'm pretty sure this won't be a problem.

The end result will be a cell array that contains all of your cities. Once you're done with this .mat file, you can delete it from your computer.

Assuming that you only want to save those variable names that start with city (i.e. city1, ..., city20) in your workspace, try doing this:

save('data.mat', 'city*'); %// Save the variables to a MAT file
data = load('data.mat'); %// Load them back into a structure that contains fields corresponding to the variable names
cellArray = struct2cell(data); %// Convert structure to cell array
delete('data.mat'); %// Delete the temporary file

cellArray will contain all of your cities indexed from 1 up to 20. Therefore, if you want to access a particular city, simply do:

city = cellArray{idx};

idx is the city ID that you want to access. Therefore, if you wanted to access city15, do:

city = cellArray{15};

Upvotes: 3

Rash
Rash

Reputation: 4336

You should put them in a cell

for i = 1 : 20
    eval(['A{',num2str(i),'} = city',num2str(i)]);
end

I don't see other choice but to use eval.

Upvotes: 0

Related Questions