Hello, I have a problem when I try to assign numeric arrows to string elements of a vector

2 visualizzazioni (ultimi 30 giorni)
Let's say I want something simple as this:
>> B=rand(3,3)
B =
0.9971 0.5053 0.4919
0.6846 0.9699 0.8862
0.8670 0.8364 0.7298
>>for i=1:3
A(i,:) = cellstr(sprintf('A%d',i))
end
>> A
A =
'A1'
'A2'
'A3'
'
But now I want assign each arrow of the B matrix to each element of the A vector such that I get:
A1= [ 0.9971, 0.5053, 0.4919 ]
A2= [ 0.6846, 0.9699, 0.8862 ]
A3= [ 0.8670, 0.8364, 0.7298 ]
What's the best way to do that? It might be piece of cake for many of you but still I am struggling with this a lot.
I tried using:
>> for j=1:length(A)
A{j}=B(j,:)
end
But in the end I get:
A =
[1x3 double]
[1x3 double]
[1x3 double]
Which is not what I expected. Please I would appreciate some help

Risposta accettata

Star Strider
Star Strider il 21 Dic 2014
Since as you have defined it, ‘A’ is a cell array, parentheses ‘()’ address each element of the cell. To address the elements in a particular cell, use the curly bracket ‘{}’ notation.
This works:
A{1}+2
and using your ‘B’ matrix, produces:
ans =
2.9971 2.5053 2.4919

Più risposte (2)

Stephen23
Stephen23 il 21 Dic 2014
What is an "arrow"? It is not clear exactly what you want to happen, nor what the problem is with the results that you get.
The allocation that you used
for j=1:length(A)
A{j} = B(j,:);
end
worked exactly as it should: it places each row of B into one cell of A, and this seems to match what you are asking for. Perhaps the display formatting '[1x3 double]' is confusing for you: never fear, your data is actually still there! Just use the workspace to view to open the variable and view it is more detail.
Note: do not use j as your loop variable, as this is the name of the inbuilt imaginary unit.

Edgar
Edgar il 21 Dic 2014
Modificato: Edgar il 21 Dic 2014
By "arrow" I meant row. There are two problems with my results; first the rows of matrix A are not assigned to the variables I created previously (A1, A2 & A3). Second, even after obtaining matrix A, I cannot perform arithmetic operations for each element because they are regarded as cells. For instance if I want to try:
-------------------------------------------------------------
>> A(1)
ans =
[1x3 double]
>> A(1)+2
I get this:
Undefined function 'plus' for input arguments of type 'cell'.
-------------------------------------------------------------------------------------------------------------------------
I know the simple code I showed at the beginning might be away from what I would like to obtain, but I am not very familiarized with Matlab and this task seems to be very useful for me.
Thank you for the quick reply :)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by