Home > Mobile >  How to create a new matrix with a for loop in MATLAB?
How to create a new matrix with a for loop in MATLAB?

Time:09-17

I am a newbie. I have problem. I have 20 (1x100) different named vectors. I want to combine these vectors to create a 20x100 matrix with a for loop. There are the examples of vectors.

namelist=["First","B","New"]
First = [1:100]
B = [1:2:200]
New = [4:4:400]
for i = 1: length(namelist)
    new_database(i,1:end) = namelist{i}
end

But, when I want to try this I saw "The end operator must be used within an array index expression." error. I know I can do same thing with this: "new_database= [First;B;New]"

but i want to do this with a for loop. Would you help me how can fix this error? or Would you explain me how can do this?

CodePudding user response:

Your problem is with this line:

new_database(i,1:end) = namelist{i}

the curly braces are used with cells, exclusively and there is no need to use range indexing as you do (i, 1:end)

Generally, it is better practice to assign character arrays or strings to cells.

One question, what are you doing with the 'First', 'New' and 'B' ranges arrays?

Something like:

namelist=["First","B","New"]

First = [1:100];
B = [1:2:200];
New = [4:4:400];

new_database = cell(1, length(namelist));

for i = 1: length(namelist)   % or length(new_database)
    new_database{i} = namelist(i)
end

which generates this output:

enter image description here

EDIT: My apologies, now I see what you are trying to accomplish. You are building a database from a series of arrays, correct?

Following my previous response, you must consider some points:

1 Your new_database should be square. Regardless of the dimensions of the arrays you are passing to it, if you form a cell from them, you will invariably have empty cells if no data is passed to those rows or columns

2 In some cases, you don't need to use for-loops, where simple indexing might suffice your case problem. Consider the following example using cellstr:

titles = ["Position", "Fruits", "Mythical creatures"] 
A = ["One", "Two", "Three"];
B = ["Apple", "Banana", "Durian"];
C = ["Dragon", "Cat", "Hamster"];

db = cell(4, 3);

db(1,:) = cellstr(titles)
db(2:end,1) = cellstr(A)
db(2:end,2) = cellstr(B)
db(2:end,3) = cellstr(C)

which generates this output:

enter image description here

CodePudding user response:

The cause of "The end operator must be used within an array index expression." is that your new_database variable is not initialized yet. You have to make an empty variable before your for loop. You also have to use eval if you want to do it as described.

new_database = []
for i = 1: length(namelist)
    new_database(i,:) = eval(namelist{i})
end
  • Related