0

I have a 14 x 13 matrix of doubles and I need to loop through this matrix and save each column into a separate one-dimensional array.

Currently I have the following code:

for i = 1:14
     for j = 1:13
     if i == 1
        A(1, j) = M(1, j)
     elseif i == 2
        B(1, j) = M(2, j) ...
     end
   end
 end

This works only for the first row and I don't see how conceptually this would be correct. I don't think you need to create a separate array manually...

What is the best way to do this?

1 Answer 1

2

I would use num2cell to convert this so that each column is a separate element in a cell array. Then if necessary you can assign them to different variables with deal.

data = rand(14,13);
cellArray = num2cell(data, 1);

% And if you must assign them to variables.
[A,B,C,D,E,F,G,H,I,J,K,L,M] = deal(cellArray{:});

Alternately, you can simply access the elements of cellArray rather than assigning them to variables.

value = cellArray{1};
size(value)

    14   1

If you can't use built-in functions your best bet is to use the colon operator to grab all rows for a given column.

A = data(:,1);
B = data(:,2);

You definitely don't want to use for loops if you can help it as they are notoriously slow in MATLAB.

That being said, it may be easier to keep your data as a matrix and then perform operations on the columns. A matrix is a much cleaner data structure than having a million different variables in your workspace. It really depends on what you're trying to do with it next.

Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately I cannot use any built-in functions for that :( The assignment wants it to be done using for loops...
@Micard does it explicitly say for loops or just no built-in functions?
It doesn't say "use for loops" but I know the expectations. See, the way I showed in my code example works, but I wonder if there is a better way to do it. More procedural way.
@Micard I have updated my post with a solution not using built-in functions. This is much preferred over for loops. While for loops are common in C their use is discouraged in MATLAB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.