user7629376
user7629376

Reputation:

Matlab: Unable to perform assignment because the left and right sides have a different number of elements

labs = 1:1334;

for i = 1:1334
    labs(i) = num2str(i,'%06.f');
end

I want to put "000001" "000002" etc as strings into the "labs" array. However, it says each side has a different number of elements. Why don't they both only have one?

Upvotes: 0

Views: 1192

Answers (1)

J.A. Ferrand
J.A. Ferrand

Reputation: 218

The issue stems from the fact that labs is defined as a double array by default, meaning that its elements are expected to be numeric. In the for loop, you're trying to assign string values (using the num2str function) to the labs array which is of the class double. A workaround would be to define labs as a cell array, which can store string values.

N = 1334;
labs = cell(N,1);
for i = 1:N
    labs{i} = num2str(i,'%06.f');
end

The only caveat is that labs is now a cell array, which requires a different syntax than regular double arrays to index its elements.

Upvotes: 1

Related Questions