0

I have a 1 by 4 cell array ( 1 row and 4 columns). Every single column of that cell array contains a 4 by 4 matrix. I only want to copy the first, second and, the third row of the 4th column of every 4 by 4 matrix and create another 1 by 4 cell array which is 3 by 1 (3 rows and 1 column elements copied). I was wondering what is an efficient method of doing this?

for i=1:1:number_links
    for j=1:1:3
          O{1,i}(j,4)=T{1,i}(j,4);
   end
end
2
  • please share your code Commented Oct 30, 2018 at 3:01
  • I just did, but it is giving me a 3 by 4 matrix. I am looking for a 3 by 1 matrix in every single 1 by 4 cell array. Commented Oct 30, 2018 at 3:06

2 Answers 2

2

Banghua gives a good solution. But it is possible to hide the loop using cellfun. I'm not sure if it actually is cleaner than a plain old loop, but it is nice to know about the possibilities:

O = cellfun(@(x)x(1:3,4),T,'UniformOutput',false);

Here we're using an anonymous function @(x)x(1:3,4), which is applied to each element T{1,i}. That is, O{1,i} = T{1,i}(1:3,4), just as in Banghua's answer.

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

Comments

1

I am not sure about your code. Here is an example. I created a 1 by 4 cell array named c. Each cell is rand(4) (4 by 4 matrix of random numbers). My method is to use a for loop and change each cell by c{1,i} = c{1,i}(1:3,4). Here c{1,i}(1:3,4) gives the 1st, 2nd, and 3rd row of 4th column.

% create 1 by 4 cell array. Each cell is a 4 by 4 matrix
c = cell(1,4);
for i = 1:4
    c{1,i} = rand(4);
end
disp(c)

% change 1 by 4 cell array. Each cell is a 3 by 1 matrix
for i = 1:4
    c{1,i} = c{1,i}(1:3,4);
end
disp(c)

Output:

[4x4 double]    [4x4 double]    [4x4 double]    [4x4 double]

[3x1 double]    [3x1 double]    [3x1 double]    [3x1 double]

Comments

Your Answer

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