How can I create variables from a matrix (4 x m), so that every column is a variable ? In the code I have 2 elements (N=2), but I need to do it also with 6, 8 10 elements.

3 vues (au cours des 30 derniers jours)
N=2; % elements
L=1/N;
L=zeros(1,N)+L;
y=0:L:1;
Nf=NaN;
syms x NaN
for i=1:length(y)
if i-1==0
fa(i)=NaN;
elseif i-1==1
fa(i)=NaN;
else fa(i)=0;
end
if i-1==0
fb(i)=NaN;
else
fb(i)=(x-y(i-1))/L(i-1);
end
if i+1>N+1
fc(i)=NaN;
else
fc(i)=(y(i+1)-x)/L(i);
end
if i+1>=N+1
fd(i)=Nf;
else
fd(i)=0;
end
end
f=[fa; fb; fc; fd]
  3 commentaires
DGM
DGM le 2 Oct 2021
Modifié(e) : DGM le 2 Oct 2021
This is relevant.
Long story short: arrays are indexable programmatically. Variable names are not programmatically indexable without opening up a can of worms that you should want to avoid unless you actually like causing problems for yourself.
As dpb mentioned, there are options like structs or tables that might be more desirable for the way they allow you to describe and organize their contents.
Ravi Narasimhan
Ravi Narasimhan le 2 Oct 2021
Modifié(e) : Ravi Narasimhan le 2 Oct 2021
To pile on: I use tables a lot but also Map Containers for associating keys with values when appropriate.
e.g.
A = magic(4)
A = 4×4
16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
keySet = [1,2,3,4]; % Can be almost anything including chars if desired
valueSet = {A(:,1), A(:,2), A(:,3), A(:,4)}; % Associate a value with each key
B = containers.Map(keySet, valueSet)
B =
Map with properties: Count: 4 KeyType: double ValueType: any
B(3)
ans = 4×1
3 10 6 15
B(22) = [1 0 1 0] % Add to it. The 22 is a key vs. an array element
B =
Map with properties: Count: 5 KeyType: double ValueType: any
keys(B)
ans = 1×5 cell array
{[1]} {[2]} {[3]} {[4]} {[22]}
values(B)
ans = 1×5 cell array
{4×1 double} {4×1 double} {4×1 double} {4×1 double} {[1 0 1 0]}

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by